This is a creation in Article, where the information may have evolved or changed.
Understanding Golang's interface mainly lies in the following two points:
- Interface is a collection of methods
- Interface is a type
Simple example
package mainimport "fmt"type Animal interface { Speak() string}type Cat struct{}func (c Cat) Speak() string { return "cat"}type Dog struct{}func (d Dog) Speak() string { return "dog"}func Test(params interface{}) { fmt.Println(params)}func main() { animals := []Animal{Cat{}, Dog{}} for _, animal := range animals { fmt.Println(animal.Speak()) } Test("string") Test(123) Test(true)}
In the above code, animal is defined as an interface, and cat and dog two structures implement the method defined in the interface respectively. When interface{} is used as a function parameter, different types of parameters can be accepted.
Pointers and interface
If the code above is:
func (c Cat) Speak() string { return "cat"}
Modified to:
func (c *Cat) Speak() string { return "cat"}
The following error occurs when you run the source code again:
cannot use Cat literal (type Cat) as type Animal in array or slice literal:Cat does not implement Animal (Speak method has pointer receiver)
This is because the program thinks that Cat does not implement the Speak () method, but is implemented by *cat. This means that the struct does not implicitly convert the type when implementing an interface method.
Interface array
interface{} is very different as a function parameter and []interface{} as a formal parameter, as shown in the following example:
package mainimport ( "fmt")func PrintAll(vals []interface{}) { for _, val := range vals { fmt.Println(val) }}func main() { names := []string{"stanley", "david", "oscar"} PrintAll(names)}
The above code is not working correctly and the error message is:
cannot use names (type []string) as type []interface {} in argument to PrintAll
This indicates that there must be more than one type conversion operation before assigning a value to an array of interfaces, the correct code is as follows:
package mainimport ( "fmt")func PrintAll(vals []interface{}) { for _, val := range vals { fmt.Println(val) }}func main() { names := []string{"stanley", "david", "oscar"} vals := make([]interface{}, len(names)) for i, v := range names { vals[i] = v } PrintAll(vals)}
The above is the basic content about the use of interface.