Cannot use (* struct) as (* interface) field value

I have the following code:

// eventloop.go
type Object interface {
    ActivateSlot(name string, parameters vector.Vector);
}



// main.go
import loop "./eventloop"

// ...

const slotname = "printer"

type printer struct {
    slot loop.Slot;
}

func (p *printer) Init() {
    p.slot = loop.Slot{slotname, p}; // offending line
}

func (p *printer) ActivateSlot(name string, parameters vector.Vector) {
    fmt.Println("Slot called: ", name); 
}

When I try to compile, I get the following error:

jurily@jurily ~/workspace/go $ ./build.sh
main.go:23: cannot use p (type *printer) as type *eventloop.Object in field value

If I comment on a line with a violation, it compiles and works fine. What's going on here? What am I missing?

+3
source share
1 answer

Update: This code compiles here (all in one package):

type Object interface {
    ActivateSlot(name string, parameters vector.Vector);
}
type Slot struct {
  name string;
  stuff Object;
}

const slotname = "printer"
type printer struct {
    slot Slot;
}
func (p *printer) Init() {
    p.slot = Slot{slotname, p}; // offending line
}
func (p *printer) ActivateSlot(name string, parameters vector.Vector) {
    fmt.Println("Slot called: ", name);
}

It seems that you are missing the fact that the * printer is of type Object, and you are trying to assign it to a field of type * Object, which is another type.

In most cases, you should write it, as indicated above, without pointers to interface types, but if you need to do this, you can do it like this:

type Slot struct {
  name string;
  stuff *Object;
}
func (p *printer) Init() {
     var o Object = p;
    p.slot = Slot{slotname, &o}; // offending line
}

, p - , p *Object.

+1

Source: https://habr.com/ru/post/1724258/


All Articles