Variables often hold text or numeric data. In golang there are several types of variables,
including strings and numeric variables.

Variables can be reused in your code. Arithmetic operations can be used on numeric variables.
String variables can also be changed (sub-strings, concatenation).

Related course: Introducing Go: Build Reliable, Scalable Programs

Variables in golang

Variable declaration

Variables declaration in the Go language: variable names consist of letters, numbers, underscores, where the first letter cannot be numeric.

1
2
3
4
5
6
7
8
var (
a int
b bool
s string
apple int
bee bool
apple2 string
)

This type of factoring keyword is generally written to declare global variables and is generally defined outside of func.

When a variable is declared by a var, the system automatically gives it a zero value of that type:

1
2
3
4
5
int i //= 0
float f //= 0.0
bool b //= False
string s //= " "
pointer p // = nil

and these variables are initialized in Go.

Note If // is used, this means it’s a comment and ignored by Go.

Multiple variables can be assigned on the same line, also known as parallel assignments. For example:

1
a, b, c = 5, 7, "abc"
1
2
// simple declaration:
a, b, c := 5, 7, "abc"

The values on the right of the colon before the equal sign are assigned to the left variable in the same order, so the value of a is 5, the value of b is 7, and the value of c is “abc”.

go print variables

To output variables you can use the functions Println or Printf.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import (
"fmt"
)

func main() {
x := 1
fmt.Println(x) // prints 1
{
fmt.Println(x) // prints 1
x := 2
fmt.Println(x) // prints 2
}
fmt.Println(x) // prints 1
}

This outputs:

1
2
3
4
5
~ go run example.go
1
1
2
1

Related course: Introducing Go: Build Reliable, Scalable Programs

Strings

A string is a text variable. This can be a single character, a word, a phrase, a paragraph or even a book. A string is defined in double quotes ", like the strings s and x below.

To output a single string, you can just pass it into the string function fmt.Println(x). But to output multiple strings you need to use the special symbol %s`.

1
2
3
4
5
6
7
8
9
10
11
package main
import (
"fmt"
)

func main() {
s := "Hello"
x := "World"

fmt.Printf("%s %s\n",s,x)
}
1
2
~ go run example.go
Hello World

Numeric variables

Lets start with numeric variables. There are two main types of numeric variables in programming:

  • integers (int)
  • floating points (float).

Integer

An integer is a natural number, like 1,2,3,4. If you define a variable to be an integer, it cannot be a real number (1.5, 1.33333).

1
2
3
4
5
6
7
8
9
10
package main

import "fmt"

func main() {
x := 1
y := 2
fmt.Printf("x is %d\n", x)
fmt.Printf("y is %d\n", y)
}
1
2
3
~ go run example.go
x is 1
y is 2

To output an integer, you use the symbols %d.

Integers use the decimal system (base 10), but you can output integers in other ways like binary (base 2), octal (base 8) or hexadecimal (base 16):

1
2
3
4
5
6
7
8
9
%b	base 2
%c the character represented by the corresponding Unicode code point
%d base 10
%o base 8
%O base 8 with 0o prefix
%q a single-quoted character literal safely escaped with Go syntax.
%x base 16, with lower-case letters for a-f
%X base 16, with upper-case letters for A-F
%U Unicode format: U+1234; same as "U+%04X"

Note: If you don’t know about base 2, base 8 or base 16 don’t worry. You can skip that for now > and just use %d for integers.

Float

A floating point number is not a natural number. You can have values like Pi, 1.3333, 1.23456 and so on.

Lets do an example. We create a program that calculates the VAT for a given price.

Define a series of products, sum the price ex. VAT, then calculate the VAT and add it to the price. Copy the code below and save the file as example.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import "fmt"

func main() {
apple := 3.0
bread := 2.0
price := apple + bread

fmt.Printf("")
fmt.Printf("Price: %f\n",price)
vat := price * 0.15
fmt.Printf("VAT: %f\n",vat)
total := vat + price
fmt.Printf("Total: %f\n",total)
fmt.Printf("")
}

To output a float (any variable with a dot in the value .), you use the symbol %f.

Note: All arithmetic operations can be used on variables: division (/), substraction (-), addition (+) and multiplication (*)

1
2
3
4
~ go run example.go
Price: 5.000000
VAT: 0.750000
Total: 5.750000

In this case it outputs floating point numbers or float. This is a number which has numbers behind the dot (behind the comma in europe).

Note: In the above output there are many numbers after the dot. You can limit this by
adding a number. For 2 digits %.2f, for 3 digits %.3f etc.

1
2
3
fmt.Printf("Price:    %.2f\n",price)
fmt.Printf("VAT: %.2f\n",vat)
fmt.Printf("Total: %.2f\n",total)

Exchange variables

If you want to exchange the values of two variables, you can simply use:

1
a, b = b, a

(in Go language, eliminating the need to use the exchange function)

1
2
3
4
5
6
7
8
9
10
11
package main

import "fmt"

func main() {
a := 1
b := 2
a,b = b,a
fmt.Println(a)
fmt.Println(b)
}

If you run the code, you will see that variable a and b have changed value.

1
2
3
4
~ go run example.go
2
1
~

blank identifier

The blank identifier is used to abandon the value, such as the value of 5 is abandoned in ` , b = 5, 7.

1
_, b = 5, 7

_ is actually a write-only variable and you cannot get its value. This is done because you must use all of the declared variables in the Go language, but sometimes you do not need to use all the return values you get from a function.

Because the Go language has a mandatory requirement, you must use the declared variable within the function, but the global variable that is not used is no problem.In order to avoid unused variables, the code will fail to compile, and we can change the unused variable to _.

nil value

The nil designator is used to represent a “zero value” of interface, function, maps, slices, and channels.If you do not specify the type of variable, the compiler will not be able to compile your code because it cannot guess a specific type.

1
2
3
4
5
package main
func main() {
var x = nil
_ = x
}

adding an element in a slice of nil is no problem, but doing the same thing to one map will generate a runtime panic:

1
2
3
4
5
package main
func main() {
var m map[string]int
m["one"] = 1 //error
}

string is not nil

This is a place that requires attention for developers who often use nil assignment string variables.

1
var str string = " "

" " is the zero value of the string and the writing below is the same as the above:

1
var str string

Video

Video tutorial below:

Exercises

  1. Calculate the year given the date of birth and age
  2. Create a program that calculates the average weight of 5 people.

Download Answers

Related course: Introducing Go: Build Reliable, Scalable Programs