12345678910111213141516171819202122232425262728293031 |
package main
import (
"fmt"
)
type LesssAdder interface {
Less(b Integer) bool
Add(b Integer)
}
type Integer int
func (a Integer) Less(b Integer) bool {
return a < b
}
func (a *Integer) Add(b Integer) {
*a += b
}
func main() {
var a Integer = 1
var b LesssAdder = &a
fmt.Println(b)
//var c LesssAdder = a
//Error:Integer does not implement LesssAdder
//(Add method has pointer receiver)
}
|
The go language can be based on the following functions:
?
1 |
func (a Integer) Less(b Integer) bool |
Automatically generate a new less () method
?
1 |
func (a *Integer) Less(b Integer) bool |
Thus, the type *integer has both Less()
a method and a Add()
method to satisfy the Lessadder interface. And according to
?
1 |
func (a *Integer) Add(b Integer) |
This function cannot generate the following member methods:
?
123 |
func(a Integer) Add(b Integer) { (&a).Add(b) } |
Because (&a).Add()
only the function parameter A is changed, there is no effect on the object that is actually being manipulated externally (value passing), which does not conform to the user's expectations. So the go language does not automatically generate this function for it. Therefore, the type integer only has the less () method, the missing Add()
method, and the Lessaddr interface is not satisfied. (It can be understood that object functions of pointer types are readable and writable, non-pointer-type Object functions are read-only) assign one interface to another interface in the go language, as long as two interfaces have the same list of methods (the order does not matter), then they are equivalent and can be assigned to each other. If the method list of the A interface is a subset of the method list of interface B, then interface B can be assigned to interface A, but the reverse is not possible and cannot be compiled.