Golang Essentials for C & C++ Developers: Part III

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.

Advertisements

One thought on “Golang Essentials for C & C++ Developers: Part III

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.