Golang / GoLang Basics Interview Questions
What is the difference between a type definition and a type alias in Go?
Go has two ways to give a new name to a type, with importantly different semantics. Understanding this prevents subtle type-safety bugs and confusing compiler errors.
| Aspect | Type Definition: type T U | Type Alias: type T = U |
|---|---|---|
| Creates new type? | YES — T and U are distinct types | NO — T is just another name for U |
| Methods of U inherited? | No — T starts with no methods | Yes — T and U are identical |
| T → U assignment | Requires explicit conversion: U(t) | No conversion needed |
| Use for | Adding type safety, defining method sets | Code migration, readability aliases |
// TYPE DEFINITION — new type with type safety
type Celsius float64
type Fahrenheit float64
func (c Celsius) ToFahrenheit() Fahrenheit {
return Fahrenheit(c*9/5 + 32)
}
var bodyTemp Celsius = 37.0
// var t Fahrenheit = bodyTemp // COMPILE ERROR — different types!
var t Fahrenheit = bodyTemp.ToFahrenheit() // OK
// Prevents bugs: you cannot accidentally mix temperatures
func setOven(temp Celsius) { /* ... */ }
// setOven(Fahrenheit(350)) // COMPILE ERROR — type safety!
setOven(Celsius(180)) // OK
// TYPE ALIAS — same type, different name
type MyString = string
var s1 string = "hello"
var s2 MyString = s1 // OK — same type
s1 = s2 // OK — no conversion
// Built-in aliases you already use:
// byte = uint8
// rune = int32
// any = interface{}
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...
