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

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