我在Golang工作,我正在尝试使用接口来组合一组使用类似方法的结构。简而言之,我有这个:
type Person interface {
BasicInfo() MemberBasicInfo
}
type MemberBasicInfo struct {
ID uint
MemberFirstName string
MemberNickname string
MemberEmail string
}
然后,应该作为接口的结构:
func (member *Member) BasicInfo() MemberBasicInfo{
return MemberBasicInfo{
ID: member.ID,
...other mapping here...
}
}
func (user *User) BasicInfo() MemberBasicInfo{
return MemberBasicInfo{
ID: uint(user.ID),
...other mapping here...
}
}
cannot use memberData (type Member) as type Member.Person in return argument: Member does not implement Person (BasicInfo method has pointer receiver)
cannot use memberData (type User) as type Person in return argument: User does not implement Person (BasicInfo method has pointer receiver)
我错过了什么?或者我做错了什么?
答案 0 :(得分:9)
如果您的界面声明如下:
type Person interface {
BasicInfo() MemberBasicInfo
}
然后任何实现BasicInfo() MemberBasicInfo
的类型都将实现接口。
在您的情况下,您创建了此方法:
func (member *Member) BasicInfo() MemberBasicInfo
这意味着类型*Member
实现了界面。
但是......注意那里的*
。 Member
没有实现界面,*Member
是谁。
因此,在尝试为接口变量分配类型时,请确保使用指针而不是直接值。
这应该有效:
var p Person
p = &Member{}
但这不会:
var p Person
p = Member{}
答案 1 :(得分:3)
指针接收器要求您将具体类的指针分配给接口类型的变量。
func usage() {
var x Person
// Notice the ampersand '&'
x = &Member{}
x.BasicInfo()
}