Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from type alias to original type

Tags:

go

Suppose I have a type alias like this:

type myint int;

Now I have a myint type called foo. Is there any way to convert foo from a myint to an int?

like image 256
Vlad the Impala Avatar asked Sep 15 '14 04:09

Vlad the Impala


1 Answers

Use a conversion to convert a myint to an int:

package main

import "fmt"

type myint int

func main() {
    foo := myint(1) // foo has type myint
    i := int(foo)   // use type conversion to convert myint to int
    fmt.Println(i)
}

The type myint is a not an alias for int. It's a different type. For example, the expression myint(0) + int(1) does not compile because the operands are different types. There are two built-in type aliases in Go, rune and byte. Applications cannot define their own aliases.

like image 154
Simon Fox Avatar answered Nov 03 '22 00:11

Simon Fox