Search code examples
gotype-alias

Type alias vs type definition in Go


I have stumbled upon this type alias in code:

type LightSource = struct {
  R, G, B, L float32
  X, Y, Z, A float32
  //...
}

My question is: what would be the reason to use a type alias like that to define a struct, rather than doing this?

type LightSource struct {
  R, G, B, L float32
  //...etc
}

Solution


  • Difference

    • With =, it's alias type. It doesn't create a new type, it just creates a symbol to the same type.
    • Without =, it's type definition. It creates a new type.

    In usage

    • When assign value of original type:
      • alias type can assign directly, without cast.
      • new type need cast, because it's a different type.
    • Method on alias type can be used on original type; while method on type definition can't.

    Example

    type_alias_vs_new_test.go:

    package main
    
    import "testing"
    
    type (
        A = int // alias type
        B int   // new type
    )
    
    func TestTypeAliasVsNew(t *testing.T) {
        var a A = 1 // A can actually be omitted,
        println(a)
    
        var b B = 2
        println(b)
    
        var ia int
        ia = a // no need cast,
        println(ia)
    
        var ib int
        ib = int(b) // need a cast,
        println(ib)
    }