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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
