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

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

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"

  • 写回答

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 { }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题