Came across the following differences a function implementations. What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object?
type MyInterface interface {
Func (param int) float64 //just random signature
}
//MyInterfaceImpl implements MyInterface
type MyInterfaceImpl struct {
}
//actual implementation
func (myObj *MyInterfaceImpl) Func(param int) float64 {
return float64(param)
}
Example 1: the pointer to the MyInterfaceImpl
is returned when function returns an interface
func NewMyInterface() MyInterface {
return &MyInterfaceImpl{}
}
Example 2: actual object of MyInterfaceImpl
is returned when function returns the object
func NewMyInterfaceImpl() MyInterfaceImpl {
return MyInterfaceImpl{}
}
UPDATE: This piece of code compiles and runs
func main() {
myIf := NewMyInterface()
fmt.Printf("Hi from inteface %f\n", myIf.Func(1000))
myImpl := NewMyInterfaceImpl()
fmt.Printf("Hi from impl %f\n", myImpl.Func(100))
}
UPDATE2: Question clarification.
This sounds weird (for me) to have a declaration of func NewMyInterface() MyInterface
and a valid implementation of return &MyInterfaceImpl{}
where a pointer is returned. I would expect to return an object of MyInterfaceImpl with return MyInterfaceImpl{}
If the language allows such types of constructs, there must be a reason for that. Eventually, I am looking for a following answer: "The function declaration returns an interface. Because the interface has a property X it is does not make sense to return an object, but the only valid option is a pointer".