http://studygolang.com/articles/3751
Go語言中的nil遠比java中的null要難以理解和掌握。
1.普通的 struct(非指針類型)的對象不能賦值為 nil,也不能和 nil 進行判等(==),即如下代碼,不能判斷 *s == nil(編譯錯誤),也不能寫:var s Student = nil。
s := new(Student) //使用new創建一個 *Student 類型對象
fmt.Println("s == nil", s == nil) //false
//fmt.Println(*s == nil) //編譯錯誤:cannot convert nil to type Student
fmt.Printf("%T\n", s) //*test.Student
fmt.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()
}
但是struct的指針對象可以賦值為 nil 或與 nil 進行判等。不過即使 *Student 類型的s3 == nil,依然可以輸出s3的類型:*Student
//var s3 Student = nil //編譯錯誤:cannot use nil as type Student in assignment
var s3 *Student = nil
fmt.Println("s3 == nil", s3 == nil) //true
fmt.Printf("%T\n", s3) //*test.Student
2.接口對象和接口對象的指針都可以賦值為 nil ,或者與 nil 判等(==)。此處所說的接口可以是 interface{},也可以是自定義接口如上述代碼中 IStudent. 使用 new 創建一個 *interface{} 類型的s2之后,該指針對象s2 !=nil ,但是該指針對象所指向的內容 *s2 == nil
s2 := new(interface{})
fmt.Println("s2 == nil", s2 == nil) //false
fmt.Println("*s2 == nil", *s2 == nil) //true
fmt.Printf("%T\n", s2) //*interface {}
fmt.Printf("%T\n", *s2) //<nil>
自定義的接口類似,如下。此時 s4 != nil,但 *s4 == nil ,因此調用 s4.speak()方法時會出現編譯錯誤。
var s4 *IStudent = new(IStudent)
fmt.Println("s4 == nil", s4 == nil) //false
fmt.Println("*s4 == nil", *s4 == nil) //true
//s4.speak() //編譯錯誤:s4.speak undefined (type *IStudent has no field or method speak)
3.將一個指針對象賦值為 nil ,然后將該指針對象賦值給一個接口(當然,該指針類型必須實現了這個接口),此時該接口對象將不為 nil .var s5 *Student = nil
var s5i IStudent = s5
fmt.Println("s5 == nil", s5 == nil) //true
fmt.Println("s5i == nil", s5i == nil) //false
posted on 2017-05-04 10:28
思月行云 閱讀(220)
評論(0) 編輯 收藏 引用 所屬分類:
Golang