This is a creation in Article, where the information may have evolved or changed.
Nil in the go language is far more difficult to understand and master than NULL in Java.
1. The ordinary struct (non-pointer type) object cannot be assigned a value of nil, and nil can be sentenced (= =), that is, the following code, can not judge *s = = Nil (compile error), also cannot write: var s Student = nil.
S: = new (Student) //Use new to create a *student type Object FMT. Println ("s = = nil", s = = nil)//false//fmt. Println (*s = = nil)//Compile error: Cannot convert nil to type studentfmt.printf ("%t\n", s) //*test. studentfmt.printf ("%t\n", *s)//test. Student<pre name= "code" class= "plain" >
Type Student Struct{}func (s *student) speak () {fmt. Println ("I am a Student.")} Type Istudent Interface {speak ()}
However, a struct's pointer object can be assigned nil or with nil. But even if the *student type S3 = = Nil, you can still output the type of S3: *student
var s3 Student = nil//Compile error: Cannot use nil as type Student in Assignmentvar s3 *student = nilfmt. Println ("S3 = = nil", S3 = = nil)//truefmt. Printf ("%t\n", S3) //*test. Student
2. Pointers to interface objects and interface objects can be assigned nil, or with nil (= =). The interface described here can be interface{}, or it can be a custom interface such as istudent in the code above. After you create a s2 of type *interface{} with new, the pointer object S2!=nil, but the pointer object points to the content *s2 = = Nil
S2: = new (interface{}) fmt. Println ("S2 = = nil", S2 = = nil) //falsefmt. Println ("*s2 = = nil", *s2 = = nil)//truefmt. Printf ("%t\n", S2) //*interface {}fmt. Printf ("%t\n", *s2) //<nil>
The custom interface is similar to the following. At this point s4! = Nil, but *s4 = = Nil, so a compilation error occurs when calling the S4.speak () method.
var s4 *istudent = new (istudent) fmt. Println ("S4 = = nil", S4 = = nil) //falsefmt. Println ("*S4 = = nil", *s4 = nil)//true//s4.speak () //Compile Error: S4.speak undefined (type *istudent has no field or method Speak
3. Assign a pointer object to nil and assign the pointer object to an interface (of course, the pointer type must implement this interface), at which point the interface object will not be nil.
var s5 *student = Nilvar s5i istudent = s5fmt. Println ("S5 = = nil", S5 = = nil) //truefmt. Println ("s5i = = nil", s5i = = nil)//false
Why is a nil so complicated? Also hope to communicate with the great God to discuss the ~