表紙 編集 差分 一覧 最近 短縮 付箋 ログイン 凍結中

Bank Account

N2Wiki > Go言語学習帳 > 05_BankAccount

BankAccount

package main
import "fmt"

type BankAccountInterface interface {
    set(x float);
    get() float;
}

func deposit(b BankAccountInterface, x float) {
    b.set(b.get() + x);
}

func withdraw(b BankAccountInterface, x float) {
    dollars := b.get() - x;
    if dollars < 0 { dollars = 0; }
    b.set(dollars);
}

type bankAccount struct {
    dollars float;
}

func (b *bankAccount) set(x float) {
    b.dollars = x;
}

func (b *bankAccount) get() float {
    return b.dollars;
}

type stockAccount struct {
    numShares float;
    pricePerShare float;
}

func (b *stockAccount) get() float {
    return b.pricePerShare * b.numShares;
}

func (b *stockAccount) set(x float) {
    b.numShares = x / b.pricePerShare;
}

func p(v ...) { 
    fmt.Println(v);
}

func main() {
    account := &bankAccount{200};
    p(account.get());
    deposit(account,50);
    p(account.get());
    withdraw(account,100);
    p(account.get());
    withdraw(account,200);
    p(account.get());
    
    stock := &stockAccount{10, 30};
    p(stock.numShares);
    p(stock.pricePerShare);
    p(stock.get());
    stock.set(150);
    p(stock.numShares);
    stock.set(600);
    p(stock.get());
    p(stock.numShares);
    deposit(stock,60);
    p(stock.get());
    p(stock.numShares);
}
  • もっとGoらしい書き方というものがあるのかもしれない・・・
  • クラスベースオブジェクト指向の考え方から頭を切り替えないとはまる。
    • かといってプロトタイプベースでもない。