2.6 Interface

Interface

One of the subtlest design features in Go are interfaces. After reading this section, you will likely be impressed by their implementation.

What is an interface

In short, an interface is a set of methods that we use to define a set of actions.

Like the examples in previous sections, both Student and Employee can SayHi(), but they don’t do the same thing.

Let’s do some more work. We’ll add one more method Sing() to them, along with the BorrowMoney() method to Student and the SpendSalary() method to Employee.

Now, Student has three methods called SayHi(), Sing() and BorrowMoney(), and Employee has SayHi(), Sing() and SpendSalary().

This combination of methods is called an interface and is implemented by both Student and Employee. So, Student and Employee implement the interface: SayHi() and Sing(). At the same time, Employee doesn’t implement the interface: BorrowMoney(), and Student doesn’t implement the interface: SpendSalary(). This is because Employee doesn’t have the method BorrowMoney() and Student doesn’t have the method SpendSalary().

Type of Interface

An interface defines a set of methods, so if a type implements all the methods we say that it implements the interface.

  1. type Human struct {
  2. name string
  3. age int
  4. phone string
  5. }
  6. type Student struct {
  7. Human
  8. school string
  9. loan float32
  10. }
  11. type Employee struct {
  12. Human
  13. company string
  14. money float32
  15. }
  16. // define interfaces
  17. type Men interface {
  18. SayHi()
  19. Sing(lyrics string)
  20. Guzzle(beerStein string)
  21. }
  22. type YoungChap interface {
  23. SayHi()
  24. Sing(song string)
  25. BorrowMoney(amount float32)
  26. }
  27. type ElderlyGent interface {
  28. SayHi()
  29. Sing(song string)
  30. SpendSalary(amount float32)
  31. }
  32. func (h *Human) SayHi() {
  33. fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
  34. }
  35. func (h *Human) Sing(lyrics string) {
  36. fmt.Println("La la, la la la, la la la la la...", lyrics)
  37. }
  38. func (h *Human) Guzzle(beerStein string) {
  39. fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
  40. }
  41. // Employee overloads SayHi
  42. func (e *Employee) SayHi() {
  43. fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
  44. e.company, e.phone) //Yes you can split into 2 lines here.
  45. }
  46. func (s *Student) BorrowMoney(amount float32) {
  47. s.loan += amount // (again and again and...)
  48. }
  49. func (e *Employee) SpendSalary(amount float32) {
  50. e.money -= amount // More vodka please!!! Get me through the day!
  51. }

We know that an interface can be implemented by any type, and one type can implement many interfaces simultaneously.

Note that any type implements the empty interface interface{} because it doesn’t have any methods and all types have zero methods by default.

Value of interface

So what kind of values can be put in the interface? If we define a variable as a type interface, any type that implements the interface can assigned to this variable.

Like the above example, if we define a variable “m” as interface Men, then any one of Student, Human or Employee can be assigned to “m”. So we could have a slice of Men, and any type that implements interface Men can assign to this slice. Be aware however that the slice of interface doesn’t have the same behavior as a slice of other types.

  1. package main
  2. import "fmt"
  3. type Human struct {
  4. name string
  5. age int
  6. phone string
  7. }
  8. type Student struct {
  9. Human
  10. school string
  11. loan float32
  12. }
  13. type Employee struct {
  14. Human
  15. company string
  16. money float32
  17. }
  18. // Interface Men implemented by Human, Student and Employee
  19. type Men interface {
  20. SayHi()
  21. Sing(lyrics string)
  22. }
  23. // method
  24. func (h Human) SayHi() {
  25. fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
  26. }
  27. // method
  28. func (h Human) Sing(lyrics string) {
  29. fmt.Println("La la la la...", lyrics)
  30. }
  31. // method
  32. func (e Employee) SayHi() {
  33. fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
  34. e.company, e.phone) //Yes you can split into 2 lines here.
  35. }
  36. func main() {
  37. mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
  38. paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
  39. sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
  40. tom := Employee{Human{"Tom", 36, "444-222-XXX"}, "Things Ltd.", 5000}
  41. // define interface i
  42. var i Men
  43. //i can store Student
  44. i = mike
  45. fmt.Println("This is Mike, a Student:")
  46. i.SayHi()
  47. i.Sing("November rain")
  48. //i can store Employee
  49. i = tom
  50. fmt.Println("This is Tom, an Employee:")
  51. i.SayHi()
  52. i.Sing("Born to be wild")
  53. // slice of Men
  54. fmt.Println("Let's use a slice of Men and see what happens")
  55. x := make([]Men, 3)
  56. // these three elements are different types but they all implemented interface Men
  57. x[0], x[1], x[2] = paul, sam, mike
  58. for _, value := range x {
  59. value.SayHi()
  60. }
  61. }

An interface is a set of abstract methods, and can be implemented by non-interface types. It cannot therefore implement itself.

Empty interface

An empty interface is an interface that doesn’t contain any methods, so all types implement an empty interface. This fact is very useful when we want to store all types at some point, and is similar to void* in C.

  1. // define a as empty interface
  2. var void interface{}
  3. // vars
  4. i := 5
  5. s := "Hello world"
  6. // a can store value of any type
  7. void = i
  8. void = s

If a function uses an empty interface as its argument type, it can accept any type; if a function uses empty interface as its return value type, it can return any type.

Method arguments of an interface

Any variable can be used in an interface. So how can we use this feature to pass any type of variable to a function?

For example we use fmt.Println a lot, but have you ever noticed that it can accept any type of argument? Looking at the open source code of fmt, we see the following definition.

  1. type Stringer interface {
  2. String() string
  3. }

This means any type that implements interface Stringer can be passed to fmt.Println as an argument. Let’s prove it.

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type Human struct {
  7. name string
  8. age int
  9. phone string
  10. }
  11. // Human implements fmt.Stringer
  12. func (h Human) String() string {
  13. return "Name:" + h.name + ", Age:" + strconv.Itoa(h.age) + " years, Contact:" + h.phone
  14. }
  15. func main() {
  16. Bob := Human{"Bob", 39, "000-7777-XXX"}
  17. fmt.Println("This Human is : ", Bob)
  18. }

Looking back to the example of Box, you will find that Color implements interface Stringer as well, so we are able to customize the print format. If we don’t implement this interface, fmt.Println prints the type with its default format.

  1. fmt.Println("The biggest one is", boxes.BiggestsColor().String())
  2. fmt.Println("The biggest one is", boxes.BiggestsColor())

Attention: If the type implemented the interface error, fmt will call Error(), so you don’t have to implement Stringer at this point.

Type of variable in an interface

If a variable is the type that implements an interface, we know that any other type that implements the same interface can be assigned to this variable. The question is how can we know the specific type stored in the interface. There are two ways which I will show you.

  • Assertion of Comma-ok pattern

Go has the syntax value, ok := element.(T). This checks to see if the variable is the type that we expect, where “value” is the value of the variable, “ok” is a variable of boolean type, “element” is the interface variable and the T is the type of assertion.

If the element is the type that we expect, ok will be true, false otherwise.

Let’s use an example to see more clearly.

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type Element interface{}
  7. type List []Element
  8. type Person struct {
  9. name string
  10. age int
  11. }
  12. func (p Person) String() string {
  13. return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
  14. }
  15. func main() {
  16. list := make(List, 3)
  17. list[0] = 1 // an int
  18. list[1] = "Hello" // a string
  19. list[2] = Person{"Dennis", 70}
  20. for index, element := range list {
  21. if value, ok := element.(int); ok {
  22. fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
  23. } else if value, ok := element.(string); ok {
  24. fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
  25. } else if value, ok := element.(Person); ok {
  26. fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
  27. } else {
  28. fmt.Printf("list[%d] is of a different type\n", index)
  29. }
  30. }
  31. }

It’s quite easy to use this pattern, but if we have many types to test, we’d better use switch.

  • switch test

Let’s use switch to rewrite the above example.

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type Element interface{}
  7. type List []Element
  8. type Person struct {
  9. name string
  10. age int
  11. }
  12. func (p Person) String() string {
  13. return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
  14. }
  15. func main() {
  16. list := make(List, 3)
  17. list[0] = 1 //an int
  18. list[1] = "Hello" //a string
  19. list[2] = Person{"Dennis", 70}
  20. for index, element := range list {
  21. switch value := element.(type) {
  22. case int:
  23. fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
  24. case string:
  25. fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
  26. case Person:
  27. fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
  28. default:
  29. fmt.Println("list[%d] is of a different type", index)
  30. }
  31. }
  32. }

One thing you should remember is that element.(type) cannot be used outside of the switch body, which means in that case you have to use the comma-ok pattern .

Embedded interfaces

The most beautiful thing is that Go has a lot of built-in logic syntax, such as anonymous fields in struct. Not suprisingly, we can use interfaces as anonymous fields as well, but we call them Embedded interfaces. Here, we follow the same rules as anonymous fields. More specifically, if an interface has another interface embedded within it, it will behave as if it has all the methods that the embedded interface has.

We can see that the source file in container/heap has the following definition:

  1. type Interface interface {
  2. sort.Interface // embedded sort.Interface
  3. Push(x interface{}) //a Push method to push elements into the heap
  4. Pop() interface{} //a Pop method that pops elements from the heap
  5. }

We see that sort.Interface is an embedded interface, so the above Interface has the three methods contained within the sort.Interface implicitly.

  1. type Interface interface {
  2. // Len is the number of elements in the collection.
  3. Len() int
  4. // Less returns whether the element with index i should sort
  5. // before the element with index j.
  6. Less(i, j int) bool
  7. // Swap swaps the elements with indexes i and j.
  8. Swap(i, j int)
  9. }

Another example is the io.ReadWriter in package io.

  1. // io.ReadWriter
  2. type ReadWriter interface {
  3. Reader
  4. Writer
  5. }

Reflection

Reflection in Go is used for determining information at runtime. We use the reflect package, and The Laws of Reflection post explains how reflect works in Go.

There are three steps involved when using reflect. First, we need to convert an interface to reflect types (reflect.Type or reflect.Value, this depends on the situation).

  1. t := reflect.TypeOf(i) // get meta-data in type i, and use t to get all elements
  2. v := reflect.ValueOf(i) // get actual value in type i, and use v to change its value

After that, we can convert the reflected types to get the values that we need.

  1. var x float64 = 3.4
  2. t := reflect.TypeOf(x)
  3. v := reflect.ValueOf(x)
  4. fmt.Println("type:", t)
  5. fmt.Println("value:", v)
  6. fmt.Println("kind is float64:", v.Kind() == reflect.Float64)

Finally, if we want to change the values of the reflected types, we need to make it modifiable. As discussed earlier, there is a difference between pass by value and pass by reference. The following code will not compile.

  1. var x float64 = 3.4
  2. v := reflect.ValueOf(x)
  3. v.SetFloat(7.1)

Instead, we must use the following code to change the values from reflect types.

  1. var x float64 = 3.4
  2. p := reflect.ValueOf(&x)
  3. v := p.Elem()
  4. v.SetFloat(7.1)

We have just discussed the basics of reflection, however you must practice more in order to understand more.