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

Tak00 · 2018-07-13 20:37:29 · 729 次点击

天哪,这格式乱了

#2
更多评论
  • 通过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

因为函数接收者接收T类型的参数时,T类型及T类型都能实现,接收T类型参数时,只有*T类型的能实现,你可以看看 go语言实战 这本书,在第五章有详细说明,或者参考go语言官方规范定义

#3