dscrb00804 2013-06-25 18:41
浏览 40
已采纳

使用一个返回值?

I want to call my function test and use one of the return values. How do I say give me the first or second value? I thought the below would give me "one" but [1] is incorrect usage causing a compile error

package main

import (
    "fmt"
)

func test() (int, string) { return 1, "one"; }

func main() {
    i,sz:=test()
    fmt.Printf("%d=%s
",i,sz)
    fmt.Printf("%s", test()[1]) //error
}
  • 写回答

2条回答 默认 最新

  • douqianxian7008 2013-06-25 21:42
    关注

    Citing the Go Language Specification:

    A primary expression of the form a[x] denotes the element of the array, slice, string or map a indexed by x. The value x is called the index or map key, respectively. [...] Otherwise [if a is not an array, slice string or map] a[x] is illegal.

    Multiple return values in Go, however, are not arrays being returned, but a separate language feature. This must be so, because an array can only hold elements of a single type, but return values can be of different types.

    But since return values are not arrays (or slices, strings or maps), the a[x] syntax is, per language spec, a syntax error. As a result, as @dav has already correctly stated, you will have to actually assign the return value to a variable in order to use it elsewhere.


    In special cases, you may be able to use this bit of trivia to avoid variable assignment:

    As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.

    Which makes the following possible:

    func foo() (int, string) {
        return 42, "test";
    }
    
    func bar(x int, s string) {
        fmt.Println("Int: ", x);
        fmt.Println("String: ", s);
    }
    
    func main() {
        bar(foo())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证