dtypj3308 2015-03-11 16:34
浏览 79
已采纳

如何声明由Go中返回多个值的函数调用实例化的多个变量?

Let's say I have a function:

func foo() (bool, string) { ... }

And then I wish to declare two variables b and s, initialized with values returned by the function call foo(). I'm aware I can do this using the "shorthand" syntax which omits type annotations:

b, s := foo();

However, I do not wish to use this shorthand syntax. I wish to use the var syntax with a variable name and expected type. I have tried this:

var b bool, s string = foo();

However, this gives me a syntax error. What is the correct way to do this?

  • 写回答

2条回答 默认 最新

  • dongqiangteng7319 2015-03-11 16:43
    关注

    In most cases, the correct way to do this is to use the shorthand syntax. That's what it's for.

    If you don't want to use the shorthand syntax, then you can use var syntax:

    var b bool
    var s string
    b, s = foo()
    

    or

    var (
        b bool
        s string
    )
    b, s = foo()
    

    There is no "shorthand var" syntax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置