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

/Go言語学習帳/06_FluentInterface の差分

N2Wiki > Go言語学習帳 > 06_FluentInterface
ページに戻る
- #start
+ #start Fluent Interface
  #?anch -e
- **** 内容が未設定のページです
- ブラウザの「戻る」で前のページに戻ってください。
- または[[編集|EDIT]]のリンクをクリックして内容を入力してください。
+ package main
+ import "fmt"
+ 
+ type myType struct { i int; }
+ 
+ type fluent interface {
+     p() fluent;
+     add(n int) fluent;
+ }
+ 
+ func (self *myType) p() fluent {
+     fmt.Println(self.i);
+     return self;
+ }
+ 
+ func (self *myType) add(n int) fluent {
+     self.i += n;
+     return self;
+ }
+ 
+ type fluent2 interface {
+     fluent;
+     sub(n int) fluent2;
+ }   
+ 
+ func (self *myType) sub(n int) fluent2 {
+     self.i -= n;
+     return self;
+ }
+ 
+ func main() {
+     x := &myType{10};
+ //    x.sub(2).p().add(10).p().sub(3).p(); // error!
+     x.sub(2).p().add(10).p().(fluent2).sub(3).p(); // type assertion
+ 
+ }
+ |<
+ -receiverにはInterfaceを書けない。
+ -戻り値の型にはInterfaceが書ける。
+ -Interfaceは継承(?)できる。
+ -Interfaceに定義されていないメソッドを呼ぼうとするとコンパイルエラー
+ -Type Assertionするとコンパイルが通り実行時に型変換。
+ -Google先生、SelfTypeか型変数がほしいです・・・。
+ >|
  #end
»