what’s empty interface in go

tags: learning go programming

content

  • an interface is just a collection of method signatures
  • an empty interface means the collection is empty, i.e., there’s no method in the collection
    • in other words, it requires no method to be implemented
  • so it’s basically a wildcard, any type satisfies empty interface

example

implement a map in go (like dictionary in python) where each value might have values of different type

  • in python
my_dict = {
	"a": "a",
	"b": 1
}
  • in go, you have to define a type for value
strMap := map[string]string{ ... }
  • in this case, we essentially want a generic type for values (any types)
anyMap := map[string]any { ... }

Note

note that, any is just an alias for empty interface interface{}.

  • so the above go code is the same as:
anyMap := map[string]interface{} { ... }

up

down

reference