Type aliases in Golang provide a way to create alternative names for existing types. They allow developers to assign a different name to an existing type, without introducing any new functionality or behavior.
You can provide more descriptive names for types. Therefore, you don't have to use the same generic names everywhere which will improve code readability and maintainability.
In this blog post, you will learn everything about type aliases in Golang – how you can create type aliases and how to use them in your code.
We will also compare it with the type definition which is another way to give custom names for your types. But there are a few differences. We will discuss everything in this lesson.
Creating Type Aliases in Golang
You already know why we use type aliases in our code. But to create aliases for your types, you have to follow a pattern.
To create a type alias, use the following syntax:
type NewTypeName = ExistingType
You need to use the type keyword to create a type alias followed by the name. Then provide the existing type from what you want to create your alias after the equal sign.
You can use the new name interchangeably with the original type throughout your code. Assignments and operations between the alias and the original type can be done seamlessly, as they share the same underlying type.
package main
import "fmt"
func main() {
// Creating type alias for float64
type Celsius = float64
// Using type alias as a type
var temp Celsius = 27.9
fmt.Printf("Temperature: %f\n", temp)
}
I have created an alias for float64
type called Celsius
. Now you can use this alias to represent floating point numbers.
When you use this alias in your code, it helps you to understand that you are working with temperatures. This is the main advantage of using type aliases instead of default names.
Here I am creating the temp
variable and setting its type to Celsius
as a regular type. But if you use shorthand syntax to create variables, you can't specify the type.
In this case, you need to use type aliases differently for the variable declaration with the shorthand syntax.
package main
import "fmt"
func main() {
// Creating type alias for float64
type Celsius = float64
// Using type alias as a type
temp := Celsius(27.9)
fmt.Printf("Temperature: %f\n", temp)
}
When you use the :=
sign to create your variables, you have to call your alias like a function and provide the value in between the parenthesis.
When you create a variable using an alias, you can also assign it to another variable if their underlying types are the same.
package main
import "fmt"
func main() {
// Creating type alias for float64
type Celsius = float64
// Using type alias as a type
var temp Celsius = 27.9
var a float64 = temp
fmt.Printf("Temperature: %f\n", a)
}
Here Celsius
is an alias for float64
type. When you create temp
variable using the Celsius alias, it uses the float64
type.
Now when you create another variable and set its type as float64
, you can use the temp
as its value. Because both of them are using the same float64
type.
Also Read: Golang Variable: Different Ways to Create Variables in Golang
Use of Type Definitions in Golang
Before introducing type alias in Golang, we had to use type definitions to give custom names to our types. When you use type definition in Golang, it creates a new distinct type based on the existing type.
This is the syntax for type definition in Golang:
type CustomType underlyingType
The type definition uses the type
keyword followed by a name and the underlying type. We mainly use it to create a custom type.
Here, CustomType
is the name of your custom type, and underlyingType
is the existing type on which your custom type is based. Creating custom types allows you to define new types with distinct behaviors and properties.
package main
import "fmt"
// Custom type definition
type Celsius float64
// Method for the custom type
func (c Celsius) String() string {
return fmt.Sprintf("%.2f°C", c)
}
func main() {
temp := Celsius(23.5)
fmt.Println(temp) // Output: 23.50°C
}
In the example above, we define a custom type Celsius
based on the underlying type float64
. We also define a method String()
for the Celsius
type, which allows us to format and print Celsius
values.
You can create variables of type Celsius
and use them just like any other type. We create the temp
variable using the Celsius
type and assign 23.5 as its value.
When we print temp
, the String()
method is automatically called, providing the formatted output 23.50°C
.
By creating custom types, you can add meaningful names and behaviors to existing types, making your code more expressive and readable. You can also define additional methods specific to your custom type, allowing you to encapsulate behaviors related to that type.
package main
import "fmt"
// Custom type definition
type Celsius float64
// Method for the custom type
func (c Celsius) String() string {
return fmt.Sprintf("%.2f°C", c)
}
func main() {
var temp Celsius = 23.5
var temp2 float64 = float64(temp)
fmt.Println(a)
}
You can also set Celsius
to a variable as a regular type. But unlike a type alias, you can't assign this variable to another variable without explicitly converting it.
We have created the Celsius
type from the float64
type. When we create the temp
variable and set its type as Celsius
, you can't directly assign temp
to the temp2
variable even though it is using the same float64
type.
Type Aliases VS Type Definitions in Golang
Type Aliases and Type Definitions are two different concepts in Go, even though they may seem similar at first glance. Let's explore the differences between them:
Type Aliases | Type Definitions |
---|---|
Type aliases create alternative names for existing types. | Type definitions create entirely new types based on existing types. |
They do not create new types but provide a more descriptive name for an existing type. | They introduce a new, distinct type with its own set of behaviors and properties. |
Type aliases are mainly used for improving code readability and maintainability. | Type definitions are useful when you need to define new methods or behavior specific to the new type. |
They have the same underlying type as the original type, and assignments can be made between the alias and the original type without explicit conversions. | Assignments between the new type and the underlying type require explicit conversions. |
Type aliases cannot have additional methods or behaviors beyond those of the original type. | Type definitions can add new methods, implement interfaces, and have their own distinct behavior. |
These are the main differences between type aliases and type definitions. You can choose between them based on your requirements.
Also Read: Understanding All Data Types in Golang: A Complete Guide
Conclusion
The type alias is a powerful feature for improving code clarity and maintainability. By providing custom names for existing types, type aliases allow developers to express the intent of their code more effectively.
Throughout this blog post, you have learned how to create and use type aliases in Golang. We also touched upon the distinction between type aliases and type definitions.
Type aliases help you to give a custom name to an existing type. On the other hand, type definitions create new types from another type. Both of them have some benefits and drawbacks.
If you just want a descriptive name for a type use type aliases. Because it's easy to use and you don't have to explicitly convert before using it with the original type.
But if you need to add some custom methods and functionalities with it, you definitely have to use type definitions. If you want to work with the original type you have to explicitly convert it.