What is the difference between declare the address (&) or not once the return type is an interface?
func NewService(rep repository.Repository) Service {
// or without the "&"
return &myService{
repository: rep
}
}
CodePudding user response:
The difference is that if a method needed to implement the interface has a pointer receiver, you must return a pointer. If the method instead has a value receiver, you can use either. For example:
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())
}
CodePudding user response:
this question boils down to assignability of an interface.
https://golang.org/ref/spec#Assignability
A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies: ...
- T is an interface type and x implements T. ...
https://golang.org/ref/spec#Interface_types
An interface type specifies a method set called its interface.
https://golang.org/ref/spec#Method_sets
The method set of a type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T)
The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.
What is the difference between declare the address (&) or not once the return type is an interface?
A build error.
The Effective Go has a chapter about the differences between pointer and value receivers.