morimotoyuuki111 / Go4

0 stars 0 forks source link

Stringersについて #17

Closed morimotoyuuki111 closed 2 years ago

morimotoyuuki111 commented 2 years ago

Stringers

package main //パッケージを宣言

import "fmt" //fmtパッケージをインポート

type Person struct { //構造体 Person構造体の名前
    Name string //typeは新しい方を定義する string型
      Age  int //int型
}

func (p Person) String() string { //Person構造体のString()関数をメソッドで使用する
    return fmt.Sprintf("%v (%v years)", p.Name, p.Age) //String()関数を終了
}

func main() {
    a := Person{"Arthur Dent", 42} //変数aにPerson{"Arthur Dent", 42}が代入
    z := Person{"Zaphod Beeblebrox", 9001} //変数ZにPerson{"Zaphod Beeblebrox", 9001}が代入
    fmt.Println(a, z)
}

出力結果
Arthur Dent (42 years) Zaphod Beeblebrox (9001 years)

質問1

上記のサンプルコードの理解は合っていますか?

totsumaru commented 2 years ago

OKです!!