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

/Go言語学習帳/05_BankAccount の差分

N2Wiki > Go言語学習帳 > 05_BankAccount
ページに戻る
- #start
+ #start Bank Account
  #?anch -e
- **** 内容が未設定のページです
- ブラウザの「戻る」で前のページに戻ってください。
- または[[編集|EDIT]]のリンクをクリックして内容を入力してください。
+ 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らしい書き方というものがあるのかもしれない・・・
+ -クラスベースオブジェクト指向の考え方から頭を切り替えないとはまる。
+ --かといってプロトタイプベースでもない。
+ >|
  #end
»