Go 将任何结构作为接口方法传入
我正在尝试创建一个接口,该接口有一个将任何结构作为输入的方法。正在尝试使用Go 将任何结构作为接口方法传入,go,Go,我正在尝试创建一个接口,该接口有一个将任何结构作为输入的方法。正在尝试使用*接口,但不起作用。代码: package main import ( "fmt" ) type Marshallable interface { marshal() (*interface{}, error) } func Marshal(marshallable Marshallable) (error) { fmt.Println(marshallable.marsh
*接口
,但不起作用。代码:
package main
import (
"fmt"
)
type Marshallable interface {
marshal() (*interface{}, error)
}
func Marshal(marshallable Marshallable) (error) {
fmt.Println(marshallable.marshal())
return nil
}
type Message1 struct {
message string
}
func (m *Message1) marshal() (m2 *Message2, err error) {
return nil, nil
}
type Message2 struct {
message string
}
func main(){
var m1 = Message1 {message: "Hello1"}
Marshal(m1)
}
它给出了编译器错误:
./prog.go:31:11: cannot use m1 (type Message1) as type Marshallable in argument to Marshal:
Message1 does not implement Marshallable (wrong type for marshal method)
have marshal() (*Message2, error)
want marshal() (*interface {}, error)
有什么办法可以让它工作吗
程序中有几个错误:
*接口{}
,使用接口{}
。接口{}
可用于表示“任意”Message1
结构没有实现Marshallable
,因为它不返回接口{}
,而是返回*Message2
。Go类型检查是严格的,如果它需要接口{}
,则必须返回接口{}
Message1.marshal
有一个指针接收器,因此必须向main
中的结构发送指针:这样,您传递的接口将有一个指向
m1
的指针,而不是指向其副本的指针。您的代码根本无法工作,因为消息的封送处理方法有一个指针类型的接收器,而您传递的是struct,而不是指针。因此需要在函数调用中传递&m1
在接收器和返回类型中使用ptr
无ptr(*)
带Ptr
如果我将
*接口{}
替换为*结构{}
,有什么区别?它给出的输出与我猜想的相同,struct{}
是一个空文本,而interface{}
可以接受任何结构。是的,就是这样。一个*struct{}
是指向没有字段的结构的指针。*接口{}
是指向可能包含任何类型数据的接口的指针。不要使用*接口{}
,这几乎没有必要。如果我用结构{}
替换接口{}
,有什么区别?它给出相同的输出。我猜struct{}
是一个空文本,而interface{}
可以接受任何结构,所以我想interface{}
struct{}
是数据,interface{}
有一个指向某些数据的指针。struct{}
是一个特定类型(没有字段的结构)<代码>接口{}可以是任何类型(所有类型都实现没有方法的接口)。
Marshal(&m1)