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{}
More Related questions...