Pass a result from multi-returing function to another one taking only one argument in Go

huangapple go评论91阅读模式
英文:

Pass a result from multi-returing function to another one taking only one argument in Go

问题

是的,可以直接将返回多个值的函数的结果传递给只接受一个值的函数。例如:

func MarshallCommandMap(mapToMarshall map[string]string) string {
    return string(json.Marshal(mapToMarshall))
}

上面的示例会导致编译错误:multiple-value json.Marshal() in single-value context。我知道可以通过额外的变量来获得相同的结果:

func MarshallCommandMap(mapToMarshall map[string]string) string {
    marshaledBytes, marshalingError := json.Marshal(mapToMarshall)
    if marshalingError != nil {
        panic(marshalingError)
    }
    return string(marshaledBytes)
}

但是,是否可以直接传递第一个值而不使用任何变量呢?

英文:

Is it possible to pass a result form function which returns multiple values directly to function which accepts only one? Example:

func MarshallCommandMap(mapToMarshall map[string]string) string {
	return string(json.Marshal(mapToMarshall))
}

The example above will cause compilation error:multiple-value json.Marshal() in single-value context. I know it is possible to get same result with additional variable:

func MarshallCommandMap(mapToMarshall map[string]string) string {
	marshaledBytes, marshalingError := json.Marshal(mapToMarshall)
    if (marshalingError != nil) {
        panic(marshalingError)
    }
    return string(marshaledBytes)
}

But is it possible to pass only first value direclty without any variable?

答案1

得分: 3

我认为你的意思是像Python的元组解包那样做某事。不幸的是,在Go语言中(据我所知),这是不可能的。

英文:

I think you mean doing something like python's tuple unpacking.
Unfortunately this is not possible in Go (AFAIK).

答案2

得分: 2

不,你不能,但是你的代码有两个问题。

  1. 不应该恐慌,而是返回一个错误或者返回一个空字符串。
  2. 你可以让它更短。

示例:

func MarshallCommandMap(mapToMarshall map[string]string) string {
    js, _ := json.Marshal(mapToMarshall) //忽略错误
    return string(js)
}
英文:

No you can't, however 2 things with your code.

  1. Shouldn't panic, either return an error or return an empty string.
  2. You can make it shorter.

Example :

func MarshallCommandMap(mapToMarshall map[string]string) string {
	js, _ := json.Marshal(mapToMarshall) //ignore the error
	return string(js)
}

huangapple
  • 本文由 发表于 2014年6月17日 02:50:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/24250222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定