douxiong5972 2019-05-13 23:03
浏览 104

Go接口属性未定义

I have a specific problem where I need a variable that can take the value of one or another structure. I create a userResp structure with a user field which has the value of an interface, but if I add a function that returns a sub property of user called Password, returns error. The value of user will be a struct that have the Password property.

The struct:

type userResp struct {
  user interface{}
}

the function

func (ur *userResp) password() string {
  return ur.user.Password
}

I get ur.user.Password undefined (type interface {} is interface with no methods) but the interface user can be a Admin or User struct with a Password field.

Any idea how do this, I need to work with an struct of either the user or admin and return it.

I can't use 2 functions because the logic is the same in both cases. I need the entire struct of User or Admin

  • 写回答

1条回答 默认 最新

  • dra11767 2019-05-14 00:47
    关注

    There are a couple of problems here:

    You can't call a method on an empty interface (interface{}) because the empty interface has no methods defined.

    You can't reference fields through an interface type, only methods.

    You need to determine what behavior something you set as the value of user should have and define an interface to reflect that. For example, if the only thing you need a user to be able to do is provide a password, the interface would be

    type User interface {
        Password() string
    }
    

    Your struct would then be

    type userResp struct {
      user User
    }
    

    You would then return the password like this:

    return ur.user.Password()
    

    Whatever types you want to store in the user field would have to have the Password method defined on them so they satisfy the User interface

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器