我在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)
我错过了什么?或者我做错了什么?
1> eugenioy..:
如果您的接口声明如下:
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{}