0
0

More than 1 year has passed since last update.

値レシーバとポインタレシーバ

Posted at

はじめに

Golangをちょっと触れてみたので備忘録としての自分用メモ

レシーバとは

Goにはクラスは存在しない。そのためJavaで言うインスタンスメソッドも存在しない。
一方、構造体というものを定義することができ、構造体に対してメソッドを定義することができる。

メソッドは以下の文法で記述される
func (レシーバ 構造体) メソッド名(引数) 返り値

package main

import "fmt"

func main() {
	s := Student{"nobita", 60, 60}
	fmt.Println(s.name, s.avg()) // nobita 60
}

type Student struct {
	name    string
	math    float64
	english float64
}

func (s Student) avg() (avgRes float64) {
	avgRes = (s.math + s.english) / 2
	return
}

値レシーバとポインタレシーバ

端的にまとめると

  • 値レシーバ
    • レシーバがポインタではない
    • メソッド内でレシーバの値を書き換えることができない
  • ポインタレシーバ
    • レシーバがポインタ
    • メソッド内でレシーバの値を書き換えることができる

ポインタレシーバを使ってmath及びenglishの値を書き換えるメソッドcheatを作ってみる。

package main

import "fmt"

func main() {
	s := Student{"nobita", 60, 60}
	fmt.Println(s.name, s.avg()) // nobita 60

	s.cheat()
	fmt.Println(s.name, s.avg()) // nobita 90
}

func (s *Student) cheat() {
	s.math += 30
	s.english += 30
}
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