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).

Variables in golang

Numeric variables

Lets start with numeric variables. 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 variables.XYZ

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

import "fmt"

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

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

}

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

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.