在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)
我想念什么?还是我做错了什么?
如果您的接口这样声明:
type Person interface { BasicInfo() MemberBasicInfo }
然后,任何实现a的类型BasicInfo() MemberBasicInfo都将满足该接口。
BasicInfo() MemberBasicInfo
在您的情况下,然后创建此方法:
func (member *Member) BasicInfo() MemberBasicInfo
这意味着类型*Member满足接口。
*Member
但是..注意*那里。Member没有实现该接口,而是由*Member谁来实现。
*
Member
因此,在尝试为接口变量分配类型时,请确保使用指针而不是直接值。
这应该工作:
var p Person p = &Member{}
但这不会:
var p Person p = Member{}