Go Basics: Variables
Abhinav Pandey
Posted on November 22, 2021
In the last article, I gave a small introduction to programming with Go, where we saw the tiniest possible programs and the general syntax.
Continuing on the syntax, let's take a look at some more syntax and understand how variables are declared in Go.
If you're completely new to Go, please check out the previous article:
Variables
Variables are declared using the var
keyword and are used to store values.
The following is an example of a variable declaration.
var name string = "John"
The variable name
is of type string
and is assigned the value John
.
You can also declare multiple variables at once.
var (
name string = "John"
age int = 30
)
You can also declare variables with a type but without an initial value.
var name string
You can also declare multiple variables with a type but without an initial value.
var (
name string
age int
)
Or multiple variables of the same type in a single line.
var name, occupation string
Here, name
and occupation
are of type string
.
Shorthand declaration of variables
You can also use the :=
operator to declare and assign a variable at the same time.
name := "John"
Note that the :=
operator is only valid in short variable declarations. You cannot use it outside function bodies.
When using the :=
operator, the variable is declared with the type of the right-hand side expression. The var
keyword is also not required.
Implicit type declaration
You can also declare a variable without specifying its type. In this case, the type is inferred from the initial value or a function call.
For example, the following code declares a variable age
of type int
and assigns the value 30
to it.
var age := 30
Or using a function call.
var age := getAge()
This also works for shorthand declarations.
Constants
Constants are declared using the const
keyword. They are used to store values that cannot be changed.
For example, the following code declares a constant PI
and assigns the value 3.14
to it.
const PI = 3.14
Constants can also have implicit type declarations as in the above example.
- They cannot be declared using the
:=
operator. - They cannot be declared without an initial value.
- They cannot accept a function call as an initial value.
- The type of a constant may not be explicitly declared.
Thanks for reading.
This should give you an idea of how variables are declared in Go and how the syntax compares to other programming languages.
Stay tuned for more on Go.
If you want to connect with me, you can find me on Twitter @abh1navv.
Posted on November 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.