Golang类型T和*T的区别[填坑]

思考什么时候把参数设置为T 和 *T?

  • 如果不想变量被函数或方法修改 -> T ,反之 *T
  • 如果变量是一个大的 struct 或者数组,考虑性能选择类型 *T,只创建指针

T 和 *T的调用方法集

(1)T 类型的方法可以被 *T 类型的值调用

1
2
3
4
5
6
7
8
9
10
11
12
type MyInterface interface{
try(s string)
}

type T struct{}

func(t T)try(s string){}

var mf MyInterface
mf = new(T)
# 可以这样使用
mf.try()

(2)*T 类型的方法不可以被 T类型的值调用

1
2
3
4
5
6
7
8
9
10
11
12
13
type MyInterface interface{
try(s string)
}

type T struct{}

func(t *T)try(s string){}

var mf MyInterface
t := T{}
# 这里报错
mf = t
mf.try()

总结

记住一点Go中所有的东西都是值传递,调用函数时,传入的数据都会被复制。