英文:
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
不,你不能,但是你的代码有两个问题。
- 不应该恐慌,而是返回一个错误或者返回一个空字符串。
- 你可以让它更短。
示例:
func MarshallCommandMap(mapToMarshall map[string]string) string {
js, _ := json.Marshal(mapToMarshall) //忽略错误
return string(js)
}
英文:
No you can't, however 2 things with your code.
- Shouldn't panic, either return an error or return an empty string.
- You can make it shorter.
Example :
func MarshallCommandMap(mapToMarshall map[string]string) string {
js, _ := json.Marshal(mapToMarshall) //ignore the error
return string(js)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论