Using Go's Variable Types
Get introduced to Go's variable types and learn how to declare them.
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:
v = "hello"v = 8v = 2.5
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:
v := "hello" // also can do: var v string = "hello"
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 ...