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


    In usage


    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)
    }