Type alias vs type definition in Go

Issue

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

In this case I assume this was done by mistake – the first alternative defines a type “anonymously” and then assigns an alias to it, so the end result is the same in both cases, but still the second alternative is the only correct one.

Type aliases are useful only in a few cases, e.g. as written here, they can be useful for large-scale refactoring.

Answered By – rob74

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.