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
// 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

An array with interface

var []arr interface{}{}

Written with StackEdit.

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

  1. Chetan Giridhar
    January 7, 2019 at 5:42 PM

    Good to be mindful that make() initializes the map. Else the map is nil and assigning values to it results in panic.

    Liked by 1 person

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.

%d bloggers like this: