douhe5092 2018-11-23 18:20
浏览 42
已采纳

具有多个返回值的方法的“ if”初始化语句

I would like to have initialization statement in my if statement that actually uses several methods that return several values. Example:

func HandleArgs(args ...interface{}) {
     // Some additional checks here

     if value1, ok1, value2, ok2 := args[0].(string), args[1].(string); ok1 && ok2 {
          // Do something
     }
}

Go doesn't allow me to do that, responding with error:

assignment mismatch: 4 variables but 2 values

It is even more confusing considering that compiler can easily handle one method that return 2 values:

// it is OK!
if value, ok := args[0].(string); ok {
}

Is there any way to do what I want aside of dividing one if statement into two, which is ugly?

  • 写回答

1条回答 默认 最新

  • doujiu6976 2018-11-23 19:26
    关注

    You can't use the syntax above.

    You can use scoping with curly braces like so.

    func HandleArgs(args ...interface{}) {
        // Some additional checks here
    
        { 
            // This will ensure all values will be captured inside the following scope
            value1, ok1 := args[0].(string)
            value2, ok2 := args[1].(string)
            if ok1 && ok2 {
                // Do something
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图