Impossibile utilizzare (* struct) come (* interfaccia) nel valore del campo

StackOverflow https://stackoverflow.com/questions/1817809

  •  08-07-2019
  •  | 
  •  

Domanda

Ho il seguente codice:

// 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); 
}

Quando provo a compilare, ottengo il seguente errore:

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

Se commento la linea offensiva, si compila e funziona bene. Cosa sta succedendo qui? Cosa mi sto perdendo?

È stato utile?

Soluzione

Aggiornamento: Questo codice viene compilato correttamente qui (tutti nello stesso pacchetto):

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);
}

Sembra che ciò che manca sia che * printer sia di tipo Object e si sta tentando di assegnarlo a un campo di tipo * Object, che è di tipo diverso.

Nella maggior parte dei casi lo scriveresti come sopra - senza puntatori ai tipi di interfaccia - ma se devi, puoi farlo compilare in questo modo:

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

Quindi p è un oggetto, devi prendere l'indirizzo di p per abbinare la specifica * Object .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top