断言时为什么会出现“无法分配”错误?

时间:2016-08-31 02:47:32

标签: go

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)
    }
}

1 个答案:

答案 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?
}