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】値レシーバーとポインタレシーバーの実装比較

Posted at

ポイント

値レシーバー: 値を更新しない。
ポインタレシーバー:値を更新する。

実装例

  • 値レシーバー
main.go
package main

import "fmt"

type Rectangle struct {
    width  int
    height int
}

// 値レシーバーを持つメソッド
func (r Rectangle) Area() int {
    return r.width * r.height
}

func main() {
    rect := Rectangle{width: 10, height: 5}
    fmt.Println("Area:", rect.Area()) // Area: 50

    // メソッド内で値を変更しても、元のオブジェクトには影響しない
    rect.width = 20
    fmt.Println("Area:", rect.Area()) // Area: 50
}

  • ポインタレシーバー
main.go
package main

import "fmt"

type Rectangle struct {
    width  int
    height int
}

// ポインタレシーバーを持つメソッド
func (r *Rectangle) DoubleSize() {
    r.width *= 2
    r.height *= 2
}

func main() {
    rect := &Rectangle{width: 10, height: 5}
    fmt.Println("Width:", rect.width, "Height:", rect.height) // Width: 10 Height: 5

    // メソッド内でオブジェクトの値を変更する
    rect.DoubleSize()
    fmt.Println("Width:", rect.width, "Height:", rect.height) // Width: 20 Height: 10
}

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?