Type alias:
type A = string
Type definition:
type A string
What is the difference between them? I can't understand from spec
type A = string
creates an alias for string
. Whenever you use A
in your code, it works just like string
. So for example, you can't define methods on it.
type A string
defines a new type, which has the same representation as string
. You can convert between an A
and string
at zero cost (because they are the same), but you can define methods on your new type, and reflection will know about the type A
.
For example (on the playground)
package main
import (
"fmt"
)
type A = string
type B string
func main() {
var a A = "hello"
var b B = "hello"
fmt.Printf("a is %T\nb is %T\n", a, b)
}
Output:
a is string
b is main.B