The Empty Interface
- An empty interface is used when type of a variable is unknown.
- There are scenarios such as printf function, raw buffers where you would not know the type.
Use case
// Definition of a map is --> var map[key]value
// If we do not know the type of the value and want
// to use the map for generic types, then an empty
// interface helps
// scenario 1: map value type is unknown
var mymap map[int] interface{}
mymap = make(map[int]interface{})
mymap[10] = "python"
mymap[21] = 22
fmt.Println(mymap[10])
fmt.Println(mymap[21])
// scenario 2: map key and value types are unknown
var mymap1 map[interface{}] interface{}
mymap1 = make(map[interface{}]interface{})
mymap1[10] = "python"
mymap1[21] = 22
mymap1["test"] = 10
fmt.Println(mymap1[10])
fmt.Println(mymap1["test"])
An array with interface
var []arr interface{}{}
Written with StackEdit.
Good to be mindful that make() initializes the map. Else the map is nil and assigning values to it results in panic.
LikeLiked by 1 person