一旦返回类型是接口,声明地址(&)与不声明地址(&)之间有什么区别?
func NewService(rep repository.Repository) Service {
// or without the "&"
return &myService{
repository: rep
}
}发布于 2021-09-14 16:51:04
区别在于,如果实现接口所需的方法有指针接收器,则必须返回指针。如果该方法有一个值接收方,则可以使用其中之一。例如:
https://play.golang.org/p/ToGKyIjIJNQ
package main
import (
"fmt"
)
type Hello interface {
Hello() string
}
type World interface {
World() string
}
type HelloWorlder interface {
Hello() string
World() string
}
type test struct{}
func (t *test) Hello() string {
return "Hello"
}
func (t test) World() string {
return "World"
}
func HelloWorld1() HelloWorlder {
return &test{}
}
// if you uncomment this, it won't compile
//func HelloWorld2() HelloWorlder {
// return test{}
//}
func main() {
greeter1 := HelloWorld1()
//greeter2 := HelloWorld2()
fmt.Println(greeter1.Hello(), greeter1.World())
//fmt.Println(greeter2.Hello(), greeter2.World())
}发布于 2021-09-14 22:23:19
这个问题归结为接口的可分配性。
https://golang.org/ref/spec#Assignability
如果适用下列条件之一,则可将
值x分配给T类型的变量("x可分配给T"):.
https://golang.org/ref/spec#Interface_types
--一个接口类型指定一个称为其接口的方法集。
https://golang.org/ref/spec#Method_sets
类型T的方法集由以接收方类型T声明的所有方法集组成。对应指针类型*T的方法集是用接收器*T或T声明的所有方法集(也包括T的方法集)。
类型的方法集确定类型实现的接口和可以使用该类型的接收器调用的方法。一旦返回类型是接口,声明地址(&)与不声明地址(&)之间有什么区别?
构建错误。
有效Go有一章介绍了指针和值接收者之间的区别。
https://stackoverflow.com/questions/69181571
复制相似问题