Empty Interface
Sometimes we have no idea about the types that can be used by the code. Therefore, Go provides us with ‘empty interfaces’ that let us deal with these values. This lesson shows us how to work with them.
Introduction
The empty or minimal interface has no methods, and so it doesn’t make any demands at all.
type Any interface{}
Any variable, any type implements it (not only reference types that inherit from Object in Java/C#), and any or Any is a good name as an alias and abbreviation!
(It is analogous to the class Object in Java and C#, the base class of all classes. So, Obj would also fit.) A variable of that interface type var val interface{}
can through assignment receive a variable of any type.
This is illustrated in the program:
package mainimport "fmt"var i = 5var str = "ABC"type Person struct {name stringage int}type Any interface{} // empty interfacefunc main() {var val Anyval = 5 // assigning integer to empty interfacefmt.Printf("val has the value: %v\n", val)val = str // assigning string to empty interfacefmt.Printf("val has the value: %v\n", val)pers1 := new(Person)pers1.name = "Rob Pike"pers1.age = 55val = pers1 // assigning *Person type variable to empty interfacefmt.Printf("val has the value: %v\n", val)switch t := val.(type) { // cases defined on type of valcase int: // if val is intfmt.Printf("Type int %T\n", t)case string: // if val is stringfmt.Printf("Type string %T\n", t)case bool: // if val is boolfmt.Printf("Type boolean %T\n", t)case *Person: // if val is *Personfmt.Printf("Type pointer to Person %T\n", *t)default: // None of the above typesfmt.Printf("Unexpected type %T", t)}}
In the above code, at line 4 and line 5, we make two global variables i
and str
, respectively, and set their values. Then, at line 7, we define a Person
type struct with two fields name
(a string) and age
(an integer). Next, at line 12, we make an empty interface Any
.
Now, look at main
. We make Any
type variable val
at line 15. In the next line, we set val
to 5. At line 18, val
gets the value of str
, so in the next line, ABC (value of str
) will be printed.
At line 20, we make pers1
a Person
pointer-type variable. In the next two lines, we give a value to the internal fields ( Rob Pike as name
and 55 as age
) of pers1
. At line 23, val1
is given the value of pers1
. In the next line, val
is printed, which prints the pers1
struct as &{Rob Pike 55}.
Now, we have switch cases ...