Skip to content

Instantly share code, notes, and snippets.

@heiwa4126
Created June 26, 2020 05:26
Show Gist options
  • Save heiwa4126/f4b26c84648d64cebe86043036753b6b to your computer and use it in GitHub Desktop.
Save heiwa4126/f4b26c84648d64cebe86043036753b6b to your computer and use it in GitHub Desktop.
インタフェースが実体を受けるかポインタを受けるかはどうやら関数の実装できまるらしい。
package main
import (
"fmt"
)
type SS interface {
DoAnything()
}
type S1 struct {
cnt int
n int
}
func (s1 *S1) DoAnything() {
s1.cnt++
fmt.Printf("(%d)n=%d\n", s1.cnt, s1.n)
}
type S2 struct {
cnt int
s string
}
func (s2 *S2) DoAnything() {
s2.cnt += 100
fmt.Printf("(%d)s=%s\n", s2.cnt, s2.s)
}
type Z1 struct {
}
func (_ Z1) DoAnything() {
fmt.Println("Do nothing")
}
func test1(ss SS) {
ss.DoAnything()
}
func test2(ss SS) {
fmt.Printf("%#v\n", ss)
}
func main() {
s1 := &S1{0, 1}
s2 := &S2{0, "Two"}
test1(s1)
test1(s2)
test1(s1)
test1(s2)
z1 := Z1{}
test2(z1)
}
@heiwa4126
Copy link
Author

heiwa4126 commented Jun 26, 2020

test1(ss SS)がであってtest1(ss *SS)でないのがすごい。実体でも参照でも受けつける。ただDoSomething()の実装によって、どちらを渡せるかは決まる(Z1とS1を比較)。まあ多くの場合はポインタだと思うけど。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment