DEV Community

Nitin Bansal
Nitin Bansal

Posted on

Simplest example to understand types, aliases and comparisons between them

#go

Have a look at this example:

func main() {
    type _a int32
    type _b _a
    type _c = _a

    var a _a = 10
    var b _b = 10
    var c _c = 10

    fmt.Println(a == _a(b))
    fmt.Println(a == c)
}
Enter fullscreen mode Exit fullscreen mode

What you see here is first fmt statement requiring a cast, whereas second one doesn't.

The reason for this is 2 simple rules:

  1. Types created from another type, even containing same exact same fields, are not directly comparable
  2. Aliases created from types are directly comparable.

For both: comparison after typecasting works perfectly well.

Sweet and simple..😊

Top comments (0)