Can go interface and nil be compared?

2 interface comparison

In Go language, the internal implementation of interface contains two fields, type T and value V, and interface can be compared using == or != .

Two interfaces are equal in the following two situations:

  • Both interfaces are equal to nil (at this time both V and T are in the unset state)
  • The types T are the same, and the corresponding values ​​V are equal.
type Stu struct {
     Name string
}

type StuInt interface{}

func main() {
     var stu1, stu2 StuInt = &Stu{"Tom"}, &Stu{"Tom"}
     var stu3, stu4 StuInt = Stu{"Tom"}, Stu{"Tom"}
     fmt.Println(stu1 == stu2) // false
     fmt.Println(stu3 == stu4) // true
}

The type corresponding to stu1 and stu2 is *Stu, and the value is the address of the Stu structure. The two addresses are different, so the result is false.

The type corresponding to stu3 and stu4 is Stu, the value is a Stu structure, and all fields are equal, so the result is True.


2 nils to compare

Two nils are not necessarily equal. The interface binds the value at runtime, and only the value of the nil interface value is nil, but it is not equal to the nil of the pointer. :

var p *int = nil
var i interface{} = nil
if(p == i){
	fmt.Println("Equal")
}

The two are not the same, only two nils are equal if they are of the same type

Guess you like

Origin blog.csdn.net/qq_48626761/article/details/132036475