Lucas Wa
Lucas Wa

Reputation: 530

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

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?

Upvotes: 1

Views: 384

Answers (2)

OneOfOne
OneOfOne

Reputation: 99205

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)
}

Upvotes: 2

fabmilo
fabmilo

Reputation: 48310

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

Upvotes: 3

Related Questions