HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMajor

Idiomatic way to do conversion/type assertion on multiple return values in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
idiomaticreturnmultiplewayvaluesconversiontypeassertion

Problem

What is the idiomatic way to cast multiple return values in Go?

Can you do it in a single line, or do you need to use temporary variables such as I've done in my example below?

package main

import "fmt"

func oneRet() interface{} {
    return "Hello"
}

func twoRet() (interface{}, error) {
    return "Hejsan", nil
}

func main() {
    // With one return value, you can simply do this
    str1 := oneRet().(string)
    fmt.Println("String 1: " + str1)

    // It is not as easy with two return values
    //str2, err := twoRet().(string) // Not possible
    // Do I really have to use a temp variable instead?
    temp, err := twoRet()
    str2 := temp.(string)
    fmt.Println("String 2: " + str2 )

    if err != nil {
        panic("unreachable")
    }   
}


By the way, is it called casting when it comes to interfaces?

i := interface.(int)

Solution

You can't do it in a single line.
Your temporary variable approach is the way to go.


By the way, is it called casting when it comes to interfaces?

It is actually called a type assertion.
A type cast conversion is different:

var a int
var b int64

a = 5
b = int64(a)

Code Snippets

var a int
var b int64

a = 5
b = int64(a)

Context

Stack Overflow Q#11403050, score: 75

Revisions (0)

No revisions yet.