type definition and type alias
tags: learning go programming diff-between
content
- in go, we have
type MyInt int // type definition
type AliasInt = int // type alias- type definition is a completely new type:
- type alias is just an alias, it’s interchangeable with the original type
func MyFunc1(i MyInt) {}
func MyFunc2(i AliaseInt) {}
myInt := MyInt(1)
aliasInt := AliaseInt(1)
justInt := 1- For
MyFunc1(MyInt), only* the exact same type works- only with an asterisk, see below go-untyped-constant
MyFunc1(myInt) // of course it works
MyFunc1(aliasInt) // nope, doesn't work
MyFunc1(justInt) // nope- but this one works!
type MyInt int
func MyFunc1(i MyInt) {}
MyFunc1(1)- for
MyFunc2(), onlyMyIntdoesn’t work!
MyFunc2(1) // of course it works
MyFunc2(myInt) // nope
MyFunc2(aliasInt) // of course it works
MyFunc2(justInt) // yes, because aliasInt is an alias for int