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

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

Can you do this on one line or do you need to use temporary variables, for example, what I did 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 this called casting when it comes to interfaces?

 i := interface.(int) 
+55
casting go return-value
Jul 09 2018-12-12T00:
source share
4 answers

You cannot do this on one line. Your temporary variable approach is the way to go.

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

This is actually called a type statement . Cast conversion is different:

 var a int var b int64 a = 5 b = int64(a) 
+53
Jul 09 '12 at 21:26
source share
 func silly() (interface{}, error) { return "silly", nil } v, err := silly() if err != nil { // handle error } s, ok := v.(string) if !ok { // the assertion failed. } 

but it is more likely that you really want to use a type switch, for example-a-this:

 switch t := v.(type) { case string: // t is a string case int : // t is an int default: // t is some other type that we didn't name. } 

Go is really more about correctness than patience.

+22
Jul 20 '12 at 13:40
source share

template.Most is a standard library approach for returning only the first return value in a single statement. This can be done similarly for your case:

 func must(v interface{}, err error) interface{} { if err != nil { panic(err) } return v } // Usage: str2 := must(twoRet()).(string) 

Using must , you basically say that there should never be an error, and if there is, then the program cannot (or at least should not) continue to work, and will panic instead.

+11
Jul 09 2018-12-12T00:
source share

Or just in one if:

 if v, ok := value.(migrater); ok { v.migrate() } 

Go will take care of casting inside the if clause and give you access to cast type properties.

+2
Mar 09 '17 at 10:53 on
source share



All Articles