LoginSignup
45
42

More than 5 years have passed since last update.

Go言語でオブジェクトを作ってみる: オブジェクト・メソッド・コンストラクタなど

Last updated at Posted at 2013-12-10

この記事の目的

  • Go言語でオブジェクトを作れるようになる
  • Go言語でメソッドを定義できるようになる
  • Go言語でコンストラクタを定義できるようになる

オブジェクトを作る

Go言語ではクラスと呼ばれるものはないらしい。

main.go
package main

import (
    "log"
)

type Money struct {
    amount   uint
    currency string
}

func main() {
    money := &Money{120, "yen"}
    log.Printf("%#v", money)
}

実行してみる

go run main.go                                                                                                                                     

結果

2013/12/10 17:28:49 &main.Money{amount:0x78, currency:"yen"}

クエリメソッドを定義してみる

状態を変更しないクエリメソッド Format を定義する:

main.go
package main

import (
    "fmt"
    "log"
)

type Money struct {
    amount   uint
    currency string
}

func (this *Money) Format() string {
    return fmt.Sprintf("%d %s", this.amount, this.currency)
}

func main() {
    money := &Money{120, "yen"}
    log.Printf("%#v", money)
    log.Print(money.Format())
}

実行しての結果

2013/12/10 17:30:41 &main.Money{amount:0x78, currency:"yen"}
2013/12/10 17:30:41 120 yen

コマンドメソッドを定義してみる

状態を変更するコマンドメソッド Add を定義する:

main.go
package main

import (
    "fmt"
    "log"
)

type Money struct {
    amount   uint
    currency string
}

func (this *Money) Format() string {
    return fmt.Sprintf("%d %s", this.amount, this.currency)
}

func (this *Money) Add(that *Money) {
    this.amount += that.amount
}

func main() {
    money := &Money{120, "yen"}
    log.Print(money.Format())
    money.Add(&Money{180, "yen"})
    log.Print(money.Format())
}

実行しての結果

2013/12/10 17:34:41 120 yen
2013/12/10 17:34:41 300 yen

コンストラクタを作る

Go言語ではJavaのコンストラクタ的なものはないみたい。代わりにファクトリー関数を定義する

main.go
package main

import (
    "fmt"
    "log"
)

type Money struct {
    amount   uint
    currency string
}

func NewMoney(amount uint) *Money {
    return &Money{amount, "yen"}
}

func (this *Money) Format() string {
    return fmt.Sprintf("%d %s", this.amount, this.currency)
}

func (this *Money) Add(that *Money) {
    this.amount += that.amount
}

func main() {
    money := NewMoney(120)
    log.Print(money.Format())
    money.Add(NewMoney(180))
    log.Print(money.Format())
}

実行結果:

2013/12/10 17:40:33 120 yen
2013/12/10 17:40:33 300 yen
45
42
1

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
45
42