req是一个接口{}和PostAccountRequest,CreateAccountRequest是struct,当我这样做时,我得到cannot assign *account.PostAccountRequest to v (type *account.CreateAccountRequest) in multiple assignment
v, ok := req.(*account.CreateAccountRequest)
if ok {
if v, ok = req.(*account.PostAccountRequest); ok {
panic(ok)
}
}
答案 0 :(得分:2)
代码片段定义了一个类型为v
的变量*account.CreateAccountRequest
。第二种类型的断言尝试将*account.PostAccountRequest
分配给变量v
。这是一个错误。
如果您创建第二个变量v
:
v, ok := req.(*account.CreateAccountRequest)
if ok {
if v, ok := req.(*account.PostAccountRequest); ok { // note ":"
panic(ok)
}
}
...但没有意义,因为v
只能是结构类型之一。
也许你正在寻找这样的东西:
var name, token string
switch v := v.(type) {
case *account.CreateAccountRequest:
// v is a *account.CreateAccountRequest in this branch of the switch
name = v.Name
token = v.Token
case *account.PostAccountRequest:
// v is a *account.PostAccountRequest in this branch of the switch
name = v.Name
token = v.Token
default:
// panic?
}