Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Named type assertions and conversions

Tags:

go

If I have a custom type that simply redefines a pre-defined type with a name:

type Answer string

And I try to use it in a function that accepts the pre-defined type:

func acceptMe(str string) {
    fmt.Println(str)
}

func main() {
    type Answer string
    var ans Answer = "hello"

    // cannot use ans (type Answer) as type string in function argument
    acceptMe(ans)          
    // invalid type assertion: ans.(string) (non-interface type Answer on left)
    acceptMe(ans.(string)) 
    // Does work, but I don't understand why if the previous doesn't:
    acceptMe(string(ans))
}

Why does the type assertion fail, but the conversion work?

like image 349
atp Avatar asked Sep 09 '13 05:09

atp


People also ask

Does Go support type conversion?

Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn't support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible.

What is type assertion in Go?

A type assertion provides access to an interface value's underlying concrete value. t := i.(T) This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t . If i does not hold a T , the statement will trigger a panic.

What assertion does perform a type conversion and compare two value?

A type assertion brings out the concrete type underlying the interface, while type conversions change the way you can use a variable between two concrete types that have the same data structure.

What is type switch in GoLang?

A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable.


1 Answers

Type assertion works for interfaces only. Interface can have arbitrary underlying type, so we have type assertion and type switch to the rescue. Type assertion returns bool as the second return value to indicate if assertion was successful.

Your custom type Answer can have only one underlying type. You already know the exact type - Answer and the underlying type - string. You don't need assertions, since conversion to the underlying type will always be successful.

Old answer:

Just convert your custom type to string. The conversion will succeed since your custom type has string as an underlying type. The conversion syntax: string(ans). Go Play

like image 186
Kluyg Avatar answered Oct 13 '22 16:10

Kluyg