LoginSignup
14
11

More than 5 years have passed since last update.

structとnilの比較

Last updated at Posted at 2014-10-11
type Point struct {
    x, y int
}

func main() {
    point := Point{x: 20, y: 50}
    if point == nil {
        fmt.Println("point is nil")
    }
}

こんな感じにpoint == nilのように比較するとコンパイルエラーなります。
cannot convert nil to type Point

要は値とnilを比較するのがダメなので、
&point == nilのように参照と比較するとすれば良いです。

2014/10/15 追記
コメント頂きましたが、サンプルコードでは zero value で初期化されているので決してtrueになりませんが参照と比較しないとダメということで。
goのnil判定は思ったよりも複雑なようなので、タイトル「nilの判定方法」から変更しました。

14
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
11