Created
November 11, 2018 13:59
-
-
Save tokubass/53d1050b4743fd0245fd9a220d7521bb to your computer and use it in GitHub Desktop.
レシーバーがポインタかそうでないかの挙動
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type FooIface interface { | |
Run() | |
RunPointer() | |
} | |
type Foo struct { | |
Value string | |
} | |
func (s *Foo) RunPointer() { | |
fmt.Printf("pointer %s\n",s.Value) | |
return | |
} | |
func (s Foo) Run() { | |
fmt.Printf("non-pointer %s\n",s.Value) | |
return | |
} | |
func main() { | |
//構造体の場合、レシーバーがpointerでもnon-pointerでも暗黙的に解釈して実行してくれる | |
f := Foo{Value: "100"} | |
f.Run() | |
f.RunPointer() | |
fmt.Println("") | |
fi := FooIface(&f) | |
fi.Run() | |
fi.RunPointer() | |
// (s *Foo) RunPointer でコンパイルエラー。 (s Foo)ならok. | |
//./main.go:41:15: cannot convert f (type Foo) to type FooIface: | |
//Foo does not implement FooIface (RunPointer method has pointer receiver) | |
fi = FooIface(f) | |
fi.Run() | |
fi.RunPointer() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment