Interface interface
An interface is a set of method signatures to which all subclasses that implement the signature can be assigned.
There are two types of interfaces used in GO :1. Used as type signatures and 2. Empty interfaces (without method signatures)
Used as a type signature
type Abser interface {
Abs() float64
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs(a) float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main(a) {
var a Abser
v := Vertex{3.4}
a = &v // a *Vertex implements Abser
// V is a Vertex (instead of *Vertex)
// when v.abs () is called, it is actually converted to (&v).abs ()
// So Abser is not implemented
// The following is an error code
a = v
fmt.Println(a.Abs())
}
Copy the code
Empty interface
An empty interface is an interface that does not have any method signature and can accept any type of value
func main(a) {
var i interface{}
i = 1
i = 1.1
i = "1"
i = map[string]interface{}{}
i = []int{}
i = true
}
Copy the code
Interface with nil
An interface is similar to a structure where an interface variable records the value it actually points to and the type of that value
type interface struct{
data interface{}
type Type
}
Copy the code
In the following example, when an interface type is assigned a bool, the interface actually stores two values, a concrete value and a type
var i interface{}
i = true
fmt.Printf("%v %T",i,i) // true bool
Copy the code
Do not determine if the interface is nil
func main(a) {
var i interface{}
if i == nil {
log.Println("is nil") // is nil
}
var ipeople *IPeople
i = ipeople
log.Printf("%v %T", i, i) // nil nil
var people *People
i = people
if people == nil {
log.Println("people is nil") // people is nil
}
if i == nil {
log.Println("i is nil")}else {
log.Println("i is not nil") // i is not nil
log.Printf("%v %T", i, i) // nil *main.People
}
var people2 People
log.Printf("%v %T", people2, people2) //{} main.People
}
type People struct{}type IPeople interface{}
Copy the code
Use assertions to determine if the interface is nil
Grammar: v, ok: (type) = I.
func main(a) {
var i interface{}
i = 1
v, ok := i.(int)
log.Println(v, ok) // 1 true
var people *People
i = people
people, ok = i.(*People)
log.Println(people, ok) // <nil> true
var ipeople *IPeople
i = ipeople
ipeople, ok = i.(*IPeople)
log.Println(ipeople, ok) // <nil> true
var people1 People
var ipeople1 IPeople
i = people1
people1, ok = i.(People)
log.Println(ipeople, ok) // <nil> true
i = ipeople1
ipeople1, ok = i.(IPeople)
log.Println(ipeople1, ok) // <nil> false
if ok && ipeople==nil{
// do...}}type People struct{}
type IPeople interface{}
Copy the code