I'm new to Golang. I'm sorry but I'm still confused on what's the difference between:
type <Name> <dataType>
and
type <Name> = <dataType>
Here's an example:
package main
import "fmt"
func main() {
var (
strWord Word
strText Text
)
strWord = "gopher"
strText = "golang"
fmt.Printf("strWord = %s, Type of Value = %T
", strWord, strWord)
fmt.Printf("strText = %s, Type of Value = %T
", strText, strText)
}
type Word string
type Text = string
Output
strWord = gopher, Type of Value = main.Word
strText = golang, Type of Value = string
Then, when should we use between the two?
The first is a type declaration, the second is a type alias
Docs: https://golang.org/ref/spec#Type_declarations
This allows you to create a new distinct type <Name>
, with the underlying type <datatype>
.
You could define something like:
type Password string
And then reimplement the String()
method for it so that it's never accidentally printed.
func (p Password) String() string {
return "<redacted>"
}
Type aliases are used mostly for iterative refactoring, where moving a type from one package to another would create too large a change / break too many things.
This article explains some usecases for it:
https://talks.golang.org/2016/refactor.article
But it essentially allows you to use one type as another.
package mypackage
type Foo struct {}
package other
type Bar = mypackage.Foo
You can now use other.Bar
and mypackage.Foo
interchangeably. They are the same type, with different names. Whereas type declaration is a new type.