Skip to content

Instantly share code, notes, and snippets.

@tokubass
Created November 11, 2018 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokubass/53d1050b4743fd0245fd9a220d7521bb to your computer and use it in GitHub Desktop.
Save tokubass/53d1050b4743fd0245fd9a220d7521bb to your computer and use it in GitHub Desktop.
レシーバーがポインタかそうでないかの挙動
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