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