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

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库