Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why create go types based on other?

Tags:

go

what is the purpose of defining new types in go:

type NewType OldType

since NewType have only methods declarations, so:

var x NewType

can store also OldType 'objects'. Are there any advantages?

like image 970
Sławosz Avatar asked Oct 29 '25 16:10

Sławosz


1 Answers

The reason behind naming types in general is fairly straightforward, and is much the same in most languages - being able to name complex types, like:

type Person struct{
    name String
    age  uint8
}

However, naming a type like you described, which I'll call "type aliasing" (not sure if this is used by anyone else, but it's the term I tend to use), doesn't give you the above-mentioned advantage. What it does give you, however, is the ability to add methods to existing types. Go disallows you from adding methods to existing types that you did not define yourself (ie, built-in types or types defined in other packages), so aliasing allows you to pretend that you did define them yourself, and thus add methods to them. Another good way to think about it is like a much more concise version of creating a wrapper type (as you would in an OO language like Java, for example).

So, let's say that I wanted to be able use integers as errors. In Go, the error interface simply requires a method called "Error" which returns a string. Using type aliasing, I could do:

type errorCode int

func (e errorCode) Error() string {
    return fmt.Sprintf("%d", e)
}

...and I could use integer error codes. By contrast, if I tried the following, I would get an error:

func (e int) Error() string {
    return fmt.Sprintf("%d", e)
}

To demonstrate, check out this implementation: http://play.golang.org/p/9NO6Lcdsbq

Just to clarify (because my use of the word "alias" may be misleading), two types which are otherwise equivalent (for example, int and errorCode in the above example) are not interchangeable. The Go type system treats them as fundamentally different types, although you may be able to type-cast between them.

like image 53
joshlf Avatar answered Nov 01 '25 13:11

joshlf