0
0

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 1 year has passed since last update.

Goのfor文で詰まった話

Posted at

詰まった点

user.NameでUser構造体のNameフィールドを書き換えているのに変更が正しく反映されない...

ソースコード

package main

import "fmt"

type User struct {
	Name string
	Age  int
}

func main() {
	users := [3]User{
		{"Alice", 25},
		{"Bob", 30},
		{"Charlie", 22},
	}

	for _, user := range users {
		user.Name = "太郎"
	}

	for _, user := range users {
		fmt.Println(user.Name)
	}
}

実行結果

Alice
Bob
Charlie

原因

定義されたUser構造体の配列の要素とfor文で回されているUser構造体の配列の要素は実はメモリ内ではそれぞれ別の場所に保持されている、つまり全く別の変数として扱われているため

対処法

for i := range users {
    users[i].Name = "太郎"
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?