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

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

比如下面代码: 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)
}
复制代码

Guess you like

Origin juejin.im/post/7039376312208736263
Go