-1

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)?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user1102018
  • 4,369
  • 6
  • 26
  • 33

1 Answers1

1

The quick fix to this is to make the print_item1 just accept an I rather than an pointer to I.

func print_item1(item I)

The reason for this is that *Foo satisfies the I interface but remember that *Foo is not an *I.

I would highly suggest reading Russ Cox's explanation of the implementation of interfaces

ssemilla
  • 3,900
  • 12
  • 28