LoginSignup
6
3

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-06-06

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])
}

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

6
3
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
6
3