Practical example on empty interface

Hello good day,

I am learning golang, then i stumble upon this empty interface. than i tried to google it, every example I found they are using it on fmt.Println.

Can I ask a good example how to use empty interface?

Thanks

Hey @gilcon,

Have you gone through A Tour of Go yet? For example, here is a small rundown on what the empty interface represents: https://tour.golang.org/methods/14

The gist of it is that you can represent any type as an empty interface, since an interface that contains no methods can be used as any type (since interfaces are implemented implicitly and any type can contain no methods. Lol that might sound complicated, but it’s not once you get what I mean).

If you are looking for a more complicated example, feel free to ask.

Edit: Here’s a little example for you that prints a specific message depending on what type the interface represents: https://play.golang.org/p/lTajl8KxNn

@radovskyb thank you so much.

Yes I already finish “A Tour of Go”. I am looking how it can be used on real application not just on printing output.[quote=“radovskyb, post:2, topic:5268”]
If you are looking for a more complicated example, feel free to ask.
[/quote]

Sorry I feel my post is very demanding, but if you have example using an empty interface that not just printing output, I will appreciate it.

Thanks

Hey again @gilcon,

It’s fine and no problem at all!

If you feel that it’s not to complicated to understand, you should definitely check out the implementation of sync.Pool (https://golang.org/pkg/sync/#Pool) which uses the empty interface to store any type of allocated object for later retrieval instead of specifying types that or can/can’t be used in the pool.

In this case, the empty interface is basically being used to accept any generic type for storage and retrieval, which can then be type converted on retrieval.

Edit: One other quick example to think about is if you were wanting to implement some sort of generic key/value cache, but you don’t know what types are going to be stored.

For example, a map of interface to interface can achieve this:

package main

import "fmt"

func main() {
	// Items is a cache of any type that maps to any type.
	items := make(map[interface{}]interface{})

	items[1] = "one" // Map an integer to a string.
	items["two"] = 2 // Map a string to an integer.

	fmt.Println(items)
}
1 Like

@radovskyb Thank you so much.

Anytime :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.