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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应