フィールド値で(* interface)として(* struct)を使用できません
質問
次のコードがあります:
// 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);
}
コンパイルしようとすると、次のエラーが表示されます。
jurily@jurily ~/workspace/go $ ./build.sh
main.go:23: cannot use p (type *printer) as type *eventloop.Object in field value
問題のある行をコメントアウトすると、コンパイルして正常に実行されます。ここで何が起こっていますか?何が足りないのですか?
解決
更新: このコードはここで問題なくコンパイルされます(すべて同じパッケージに含まれています):
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);
}
不足しているのは、* printerがObject型であり、* Objectという異なる型のフィールドに割り当てようとしているようです。
ほとんどの場合、インターフェイスタイプへのポインタなしで上記のように記述しますが、必要な場合は次のようにコンパイルできます。
type Slot struct {
name string;
stuff *Object;
}
func (p *printer) Init() {
var o Object = p;
p.slot = Slot{slotname, &o}; // offending line
}
したがって、 p
はオブジェクトなので、 * Object
仕様に一致するようにpのアドレスを取得する必要があります。
所属していません StackOverflow