Go 接口为何不一定能够接收值类型(但一定能接收指针类型)

1,154 阅读1分钟

总结:值无法保证一定能够取得到地址

比如下面代码: main函数里面不管是s = ServiceImpl{}还是s = &ServiceImpl{}都可以正常运行

type Service interface {
   Login(username, password string) string
}

type ServiceImpl struct{}

func (s ServiceImpl) Login(username, password string) string {
   return username + password
}

func main() {
   var s Service
   s = ServiceImpl{} 
   // s = &ServiceImpl{}
   fmt.Println(s.Login("abc", "123"))
}

但是如果是下面代码,把ServiceImpl的接收者换成指针类型,则赋值给接口的必须是指针类型:

type Service interface {
   Login(username, password string) string
}

type ServiceImpl struct{}

func (s *ServiceImpl) Login(username, password string) string {
   return username + password
}

func main() {
   var s Service
   s = &ServiceImpl{}
   fmt.Println(s.Login("abc", "123"))
}

因为像下面这样的类型,是无法取到地址的:

type Time int

func main() {
   fmt.Println(&Time(1))
}

当然,可以这样拿到地址:

type Time int

func main() {
   t := Time(1)
   fmt.Println(&t)
}

所以问题来了,为什么&Time(1)拿不到地址:

引用群里大佬的话:Time(1)是字面量,字面量不可寻址,t是变量,变量可寻址

煎鱼大佬的话是:Go不会把隐式的把Time(1)转换成变量,因此拿不到它的地址