golang中值类型/指针类型的变量区别的相关疑问

Tak00 · · 676 次点击
这网站会吃字符吗,我的星号一会在,一会不在
#5
更多评论
- 通过reflect的测试结果来看,*T确实实现了M1方法,测试代码如下: ``` package main import ( "fmt" "reflect" ) type intf interface { M1() M2() } type T struct { Name string } func(t T) M1() { t.Name = "name1" } func(t *T) M2() { t.Name = "name2" } func main() { var t1 T = T{"1"} var t2 intf = &t1 t2Type := reflect.TypeOf(t2) numMethod := t2Type.NumMethod() fmt.Println("the count of Method: ", numMethod) for i := 0; i < numMethod; i++ { fmt.Println(i, " ", t2Type.Method(i).Name, t2Type.Method(i).Type) } } ``` - 运行结果如下: ``` the count of Method: 2 0 M1 func(*main.T) 1 M2 func(*main.T) ``` - 另外,如果在以上代码中,删除 `T` 实现的 `M1()` 方法,将会报如下错误: ``` # command-line-arguments ./test.go:26:6: cannot use &t1 (type *T) as type intf in assignment: *T does not implement intf (missing M1 method) ```
#1
天哪,这格式乱了
#2