是否可以传递一个结果表单函数,它直接将多个值返回给只接受一个的函数?例如:
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)
}
但是没有任何变量只能传递第一个值direclty吗?
答案 0 :(得分:3)
我认为你的意思是做像python的元组拆包这样的事情。 不幸的是,这在Go(AFAIK)中是不可能的。
答案 1 :(得分:2)
不,你不能用你的代码做两件事。
示例:
func MarshallCommandMap(mapToMarshall map[string]string) string {
js, _ := json.Marshal(mapToMarshall) //ignore the error
return string(js)
}