goLang 之 type Method Value 和Method Expressions

soledad ·
目前使用go版本:go version go1.9.1 darwin/amd64 " methods Receiver是T,可以被T和*T Type调用; methods Receiver是*T,则只能被*T Type调用; " 这种区别已经没有了。 代码 type Integer struct { X int64 } func (I Integer) Add(a int64) { I.X += a } func (I *Integer) Sub(a int64) { I.X -= a } func Test_Integer(t *testing.T) { i1 := new(Integer) i1.Add(3) t.Logf("i1.X = %d", i1.X) i1.Sub(3) t.Logf("i1.X = %d", i1.X) i2 := Integer{} i2.Add(3) t.Logf("i2.X = %d", i2.X) i2.Sub(3) t.Logf("i2.X = %d", i2.X) } 执行命令: go test -run="Test_Integer" -v 执行结果: === RUN Test_Integer --- PASS: Test_Integer (0.00s) struct_test.go:21: i1.X = 0 struct_test.go:23: i1.X = -3 struct_test.go:27: i2.X = 0 struct_test.go:29: i2.X = -3 PASS ok go.try/maptest 0.011s
#1
更多评论
Quieting · #1 · 不到1分钟之前 目前使用go版本:go version go1.9.1 darwin/amd64 " methods Receiver是T,可以被T和T Type调用; methods Receiver是T,则只能被*T Type调用; " 这种区别已经没有了。 代码 : `type Integer struct { X int64 }` `func (I Integer) Add(a int64) { I.X += a }` ` func (I *Integer) Sub(a int64) { I.X -= a }` `func Test_Integer(t *testing.T) { ` `i1 := new(Integer) ` `i1.Add(3) ` `t.Logf("i1.X = %d", i1.X) ` `i1.Sub(3)` `t.Logf("i1.X = %d", i1.X)` `i2 := Integer{}` `i2.Add(3)` `t.Logf("i2.X = %d", i2.X)` `i2.Sub(3)` `t.Logf("i2.X = %d", i2.X)` `} ` 执行命令: go test -run="Test_Integer" -v 执行结果: `=== RUN Test_Integer` `--- PASS: Test_Integer (0.00s)` `struct_test.go:21: i1.X = 0` `struct_test.go:23: i1.X = -3` `struct_test.go:27: i2.X = 0` `struct_test.go:29: i2.X = -3` `PASS ok go.try/maptest 0.011s`
#2