2
0

More than 1 year has passed since last update.

Go言語 メソッド

Last updated at Posted at 2022-04-08

Method

任意の型に特化した関数を、定義する仕組み。
通常の関数と異なる点は、メソッド名の前にレシーバーが必要になること。

Code

// 映画タイトルのための構造体
type Movie struct {
	Directer string
	Title    string
	Year     int
}

// 映画情報を出力するメソッド
func (m *Movie) infoMovie() {
	// レシーバーの変数を介して、値を出力
	fmt.Printf("Title : %s, Directer : %s, Year : %d \n", m.Title, m.Directer, m.Year)
}

// メイン関数
func main() {

	// 映画情報を格納
	movie1 := &Movie{
		Directer: "Steven Spielberg",
		Title: "Saving Private Ryan",
		Year: 1998,
	}

	// infoMovieメソッドの呼び出し
	movie1.infoMovie()
}

Output Sample

~ $ go build main.go
~ $ ./main
Title : Saving Private Ryan, Directer : Steven Spielberg, Year : 1998

GitHub

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