So this is what I ran into, and I can't understand why the error:
package main
import (
"fmt"
)
// define a basic interface
type I interface {
get_name() string
}
// define a struct that implements the "I" interface
type Foo struct {
Name string
}
func (f *Foo) get_name() string {
return f.Name
}
// define two print functions:
// the first function accepts *I. this throws the error
// changing from *I to I solves the problem
func print_item1(item *I) {
fmt.Printf("%s\n", item.get_name())
}
// the second function accepts *Foo. works well
func print_item2(item *Foo) {
fmt.Printf("%s\n", item.get_name())
}
func main() {
print_item1(&Foo{"X"})
print_item2(&Foo{"Y"})
}
Two identical functions accept a single argument: a pointer to either the interface, or the struct that implements it.
The first one that accepts the pointer to the interface does not compile with an error item.get_name undefined (type *I is pointer to interface, not interface)
.
Changing from *I
to I
solves the error.
What I'd like to know is WHY the difference? The first function is very common as it allows a single function to be used with various structs as long as they implement the I
interface.
Also, how come that the function compiles when it is defined to accept I
but it actually receives a pointer (&Foo{}
)? Should the function expect something like Foo{}
(i.e. NOT a pointer)?