Golang / GoLang Interfaces and Object Oriented Interview Questions
How do type aliases and type definitions differ in relation to interface satisfaction in Go?
Go distinguishes between type definitions (type MyInt int) and type aliases (type MyInt = int). They behave very differently when it comes to interface satisfaction and method sets.
// TYPE DEFINITION â creates a new, distinct type type Celsius float64 type Fahrenheit float64 // Celsius and float64 are different types â no implicit conversion var c Celsius = 100.0 // var f float64 = c // COMPILE ERROR: cannot use Celsius as float64 var f float64 = float64(c) // explicit conversion required // Methods can be defined on type-defined types func (c Celsius) ToFahrenheit() Fahrenheit { return Fahrenheit(c*9/5 + 32) } // TYPE ALIAS â another name for the same type type MyFloat64 = float64 // alias: MyFloat64 IS float64 var x MyFloat64 = 3.14 var y float64 = x // OK â same type // Cannot define methods on alias types (not in the same package as the original) // Interface satisfaction: type Stringer interface { String() string } // Only defined types can have methods (and thus satisfy interfaces via those methods) func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) } var s Stringer = Celsius(100) // OK â Celsius has String() // Named function types (common for interface satisfaction) type HandlerFunc func(string) error func (f HandlerFunc) Handle(s string) error { return f(s) } // method on func type type Handler interface { Handle(string) error } var h Handler = HandlerFunc(func(s string) error { return nil })
Key rule: you can define methods on a type-defined type (creating a new type gives it its own method set). You cannot add methods on an alias type (it's the same type — adding methods would affect the original type's package). This is why type MyInt int can satisfy a new interface that int cannot — you can add methods to MyInt.
More Related questions...