LoginSignup
0
0

More than 3 years have passed since last update.

GoのnilスライスはFirestoreだとnullになるから気をつける

Posted at

問題

GoでFirestoreのドキュメントにデータを書き込んでいて、配列を期待するフィールドに何故かnullが入っていて不思議になった。
データの型としても

type Fuga struct {
    Hoge        []string         `firestore:"hoge"`
}

だし、スライスに何も入ってなかったらFirestore側には空配列入って終わりでしょって思ってた。

スライスのゼロ値はnil

https://godoc.org/cloud.google.com/go/firestore#DocumentRef.Create の以下の文章を見るに、Firestoreはあらゆる型の nilnull に扱うらしい。

nils of any type convert to Null.

スライスのゼロ値はnilなので、ただ構造体を初期化しただけだとスライスはnilのまま -> そのままfirestore側に保存するとnullになるということのようだった。
なので、構造体を初期化する時にスライスも make 使うなりしてnilではない空のスライスを作ってあげることを意識した方が良いなと思った。

0
0
0

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
0
0