LoginSignup
1

posted at

updated at

Go 言語でスライスのポインタに対して Index を指定して要素を取得する

Go 言語でスライスのポインタに対して Index を指定して要素を取得する

普通のデータ型のようにポインタ参照しようとするとできない。

構造体
type Users struct {
	Name  string
	Score *[]int
}

tanaka := Users{Name: "田中", Score: &[]int{1, 2, 3}}
satou := Users{Name: "佐藤", Score: &[]int{1, 2, 3}}
users := &[]Users{tanaka, satou}
NG パターン
for i, v := range *users {
	log.Printf("名前 %v", v.Name[i])    // こっちはポインタじゃないので問題なし
	log.Printf("スコア %v", *v.Score[i]) // こっちはポインタ参照してるのにダメ
}
// エラー: invalid operation: cannot index v.Score (variable of type *[]int)

ポインタ配列に対してインデックスを指定して要素を取得するには下記のように「()」で囲む。

OK パターン
for i, v := range *users {
	log.Printf("名前 %v", v.Name[i])
	log.Printf("スコア %v", (*v.Score)[i])
}

地味にハマるのと検索ワードに困って時間がかかったので一生忘れないように残しておきます。

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
What you can do with signing up
1