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?

お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

Goで値渡しをするかポインタ渡しをするかの基準

Last updated at Posted at 2024-06-29

構造体のフィールドの値を変更する必要があるなら、構造体のポインタで渡す。

そうでないなら、値で渡す。

値で渡した場合は、構造体のコピーが作られるため、元のデータが変更されない。

なので、基本的にポインタで渡しておき、フィールドのデータを書き換える必要がない場合や明確に元のデータを書き換えたくない場合には値で渡す。

package main

import "fmt"

type mutableUser struct {
	ID   int
	Name string
	Age  int
}

func (u *mutableUser) SetAge(age int) {
	u.Age = age
}

type immutableUser struct {
	ID   int
	Name string
	Age  int
}

func (u immutableUser) SetAge(age int) {
	u.Age = age
}

func main() {
	// Mutable
	mutableUser := mutableUser{ID: 1, Name: "Test", Age: 25}
	mutableUser.SetAge(10)
	fmt.Printf("Mutable user age: %d\n", mutableUser.Age)
	// 10

	// Immutable
	immutableUser := immutableUser{ID: 1, Name: "Test", Age: 25}
	immutableUser.SetAge(10)
	fmt.Printf("Immutable user age: %d\n", immutableUser.Age)
	// 25
}
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?