dqdfpmmi022763
2014-05-19 10:29
浏览 74
已采纳

从具有多个返回值的函数调用中仅获取特定值?

Given swap, a function that returns multiple values, and supposing it's part of some API I can't modify:

package main

import "fmt"

func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

Is it possible to use swap function and get only the first returned value, discarding the second one? I tried this:

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a)
}

ERROR: prog.go:10: b declared and not used [process exited with non-zero status]

And this is not possible too:

a := swap("hello", "world")

ERROR: prog.go:10: multiple-value swap() in single-value context

How to deal with functions that return multiple values when I don't need all the returned parts?


Code is based on "A tour of go - lesson 9"

图片转代码服务由CSDN问答提供 功能建议

给出 swap ,该函数返回多个值,并假定它是某些API的一部分 我无法修改:

 包main 
 
import“ fmt” 
 
func swap(x,y string)(string,string){
返回y  ,x 
} 
 
func main(){
a,b:= swap(“ hello”,“ world”)
 fmt.Println(a,b)
} 
   
 
 

是否可以使用 swap 函数并仅获取第一个返回值,而丢弃第二个值? 我试过这个:

  func main(){
a,b:= swap(“ hello”,“ world”)
 fmt.Println(a)
}  
 
错误:prog.go:10:已声明且未使用b [进程以非零状态退出] 
   
 
 

而且这也是不可能的:< / p>

  a:= swap(“ hello”,“ world”)
 
错误:prog.go:10:单值上下文中的多值swap()
    
 
 

当我不需要所有返回的部分时,如何处理返回多个值的函数?


代码基于“ 游学入门-第9课

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmian8108 2014-05-19 10:33
    已采纳

    Use the blank identifier _:

    a, _ := swap("hello", "world")
    

    Everything assigned to the blank identifier is silently discarded without a warning being raised. You can also use the blank identifier to add padding to structures:

    struct {
        a byte
        b byte
        c byte
        _ byte // padding
    }
    

    Another usage of the blank identifier is to discard return values when initializing global variables:

    var foo, _ = foo.NewFoo() // ignore error returned by NewFoo()
    

    And when only one value of a range is required:

    for _, v := range mySlice { }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题