Using Go's Variable Types
Explore the essentials of Go's variable types and how static typing enhances code reliability. Understand the differences between dynamic and static typing, learn common Go types, and discover how to declare variables using both long and short form syntax. This lesson helps build a strong foundation for writing type-safe Go code essential for developing efficient DevOps tooling.
We'll cover the following...
Modern programming languages are built with primitives called types. When we hear that a variable is a string or integer, we are talking about the variable’s type. With today’s programming languages, there are two common type systems used:
-
Dynamic types (also called duck typing)
-
Static types
Go is a statically typed language. For those who might be coming from languages such as Python, Perl, and PHP, then those languages are dynamically typed. In a dynamically typed language, we can create a variable and store anything in it. In those languages, the type simply indicates what is stored in the variable. Here is an example in Python:
In this case, v can store anything, and the type held by v is unknown without using some runtime checks (runtime meaning that it can't be checked at compile time). In a statically typed language, the type of the variable is set when it is created. That type cannot change. In this type of language, the type is both what is stored in the variable and what can be stored in the variable. Here is a Go example:
The v value cannot be set to any other type than a string. It might seem like Python is superior because it can store anything in its variable. But in practice, this lack of being specific means that Python ...