目錄
前言
正文
前言
使用任何編程語言都會遇到判空的問題,那么Golang如何判空呢?說真的,這種方式我還是很意外的,
正文
說到Golang的判慷訓制,確實重繪了我的認知,多少有些丑 ^_^,特別是對于自定義的結構體型別,并不是簡單的與 nil 做比較,
直接上代碼:
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
var one Person
one.Name = "xiaoming"
one.Age = 12
var two Person
if one != (Person{}) {
fmt.Println(one.Name, "的年齡是", one.Age)
} else {
fmt.Println("the person is nil")
}
if two != (Person{}) {
fmt.Println(two.Name, "的年齡是", two.Age)
} else {
fmt.Println("the person is nil")
}
// if two != nil {
// fmt.Println(two.Name, "的年齡是", two.Age)
// } else {
// fmt.Println("the persion is nil")
// }
}
代碼結果:
xiaoming 的年齡是 12
the person is nil
運行結果截圖:

如果放開上面代碼的注釋,編譯器會提示如下錯誤資訊:
localhost:test lz$ go run nil.go
# command-line-arguments
./nil.go:32:9: invalid operation: two != nil (mismatched types Person and nil)
運行結果截圖:

CSDN認證博客專家
CSDN博客專家
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/250272.html
標籤:區塊鏈
