Golang 學習之“”、nil 和 len(s)的對比
1 用法
使用”“判斷string變數是否為空。
輸入:
var s string if s == "" { fmt.Println("s is empty") } else { fmt.Println("s is not empty") }
輸出:
s is empty
2 nil用法
使用nil判斷結構體的指標是否為空。
輸入:
var Str struct { name string age int } func main() { var s *Str if s == nil { fmt.Println(" s is nil ") } else { fmt.Println(" s is not nil ") } }
輸出: s is nil
3 len(s)用法
用於求陣列、切片和字典的長度。
輸入:
func main () { var s [] string if len(s) == 0 { fmt.Println("s is empty") } else { fmt.Println("s is not empty") } }