2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goでポインター型のフィールドをもつ構造体の配列をforループする処理ではまった

Last updated at Posted at 2018-03-08

JsonファイルをGoで処理するときにnull値と空文字との区別をしたいため、string型のポインター型のフィールド入った構造体を作って、その構造体の配列をfor文で回す処理を書いた。

このときはまったのが、単純にいえば、下のようなコードを実行したとき

package main

import "fmt"

// Hoge struct for test
type Hoge struct {
	Foo *string `json:foo`
}

func main() {
	var hoges [4]Hoge
	values := []string{"君", "の", "名", "は"}
	for i, value := range values {
		// v := value
		// hoges[i].Foo = &v
		// 下の1行を結局上記2行に書き換えたら問題が直った。
		hoges[i].Foo = &value
	}

	for _, hoge := range hoges {
		fmt.Print(*hoge.Foo)
		fmt.Print(" ")
	}

}

"君の名は"が出力されると思いきや"はははは"が出力されることだ。実行例

hogeがfor文全体に共通する変数であり、最終的にはhoges[i].Foo(i=0,1,2,3)を示すポインターのアドレスがすべて"は"を示すアドレスになり、結果hogesの全要素"はははは"が出力される、というロジックである。

2
3
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?