This is a creation in Article, where the information may have evolved or changed.
Tell me about my understanding of the interface Assignment of Golang .
First, The type method definition in Golang.
As
type Bird struct {
ID int
}
func (b bird) fly () {
FMT. Println ("Fly")
}
func (b *bird) eat () {
b.id++
}
The bird type has two methods,fly and eat.
Two methods are distinguished, fly is bound by (b bird),eat is bound by (b *bird).
In the application, the (b *bird) Binding method modifies the parameters in the object, while (b bird) does not.
Again, the assignment of the interface. Interface assignment can be divided into object-to-interface assignment and interface-to-interface assignment.
The assignment of an object to an interface requires that the object fully implements all methods of the interface definition.
As defined by the following interface
type Animal interface {
Fly ()
Eat ()
}
Then create the bird object to assign the value to the animal interface .
var b Bird
var ani animal = b
And
var b Bird
var ani animal = &b
Only the second of the two methods is correct, and the first one shows an error, and the error message is eat () received by the pointer.
Description The method received by the type pointer must be represented by an object pointer and passed in.
It can also be explained that the two forms of defining a type method are really different.
Then is the assignment between the interfaces.
The interface assignment is relatively simple, as long as the assigned interface implements all the methods in the assigned interface, the value can be successfully assigned.
From the way the interface is assigned, whether the interface can be successfully assigned depends on whether the method in the interface is implemented, and how the method is assigned to the method.