Variables and Constants in Go

Lucien Makutano
The Startup
Published in
5 min readSep 3, 2020
Go gopher vector data — laptrinhx

In the last few articles, we have been talking about Go data types on an abstract level. Today we will see them in action.
As mentioned before, Go is a statically typed language which means that the specification of the variable’s data type at its creation is mandatory.

Go gives us flexibility on how to specify a variable’s scope. Want to learn more about scopes? Refer to this article. For programmers who have used any statically typed language like C, C++, java etc. will find the structure of the variable declaration in Go backward.

var age int8
var name string
var isAdmin bool

yaaay🎊🎊 you have just declared your first variable in GO.

The var keyword tells the Go compiler that the value of age can change at any point in time throughout the life of the program. age is the name given to the allocated slot in memory. int8 is the data type. Confused about what a data type is? Read this article.

But again, if one knows in advanced the value to be stored, why type // var age int8 = 19? Well, Go provides us with a shorthand declaration.

age := 19
name := "tado"

Wait, but you said that when declaring a variable in Go, the data type must be specified. Where is it🤔🤔? At compile time, the Go compiler will infer the data type from the value being assigned. Use this form only if and only if the data to be stored is known at declaration time.

What about arrays, slices, maps or Struts?

Arrays

Arrays also follow the same structure as the primitive types.

// var variableName type
// array declaration
var ages [3]int8// 2D array
var unitStudents [3][20]int

In the above declaration, we are telling Go to create for us three contiguous memory slots to hold int8(bytes) data. The downside with arrays in Go is that we have to specify the number of memory slots to be created at declaration time.

Indicies are used to add or retrieve elements from an array. Note that in Computer science indices count starts from 0 up to n-1 where n is the number of slots to be created.

ages[0] = 18
ages[1] = 19
ages[2] = 20
// will throw an index out of the bound error
ages[3] = 21
// if you know the number of values
// you can use this notation
theirNames := [...]string{"Luke", "Tado", "Twist", "Stephanie"}
// to retrieve a value from the array
// indices are again used
fmt.Println(ages[0]) // output: 18

practice with arrays.

Slices

Declaring slices is a bit different from arrays. There are two ways of achieving that. One way is declaration + initialization, and the other is through the make() function which takes the data type as the first argument, the length of the slice as the second argument and the capacity as the size that the underlying array will have.

 // declaration + initialization
ages := []int{18, 19, 20, 21}
// using the make(type, len, cap) function
names:= make([]string, 5, 10)
// slices from arrays
myArray := [...]int{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
sliceFromArray1 := myArray[:4] // output: [10, 11, 12, 13]
sliceFromArray2 := myArray[5:7] // output: [15, 16]

Be careful when passing slices around because modifications to the copy are reflected in the original too, and this is because they are all sharing the same memory address or rather the same underlying array.

babyNames := []string{"Charlotte", "Aiden", "Owen", "Alexander"}
fmt.Println(babyNames) // output: [Charlotte Aiden Owen Alexander]
babyNamesCopy := babyNames
babyNamesCopy[0] = "Amelia"
fmt.Println(babyNamesCopy) // [Amelia Aiden Owen Alexander]
fmt.Println(babyNames) // [Amelia Aiden Owen Alexander]

practice with slices.

Maps

Enough of indices, let’s look at maps. In Go, a map is a key => value pair data structure that allows us to store data against some known keys for faster retrieval. Any primitive Go data type can be used to play the role of a key in a map.

// the syntax is like map[key-type]value-typetop4AfricanCountriesPopulation := map[string]int32{
"Nigeria": 206139589,
"Ethiopia": 114963588,
"Egypt": 102334404,
"DR Congo": 89561403,
}
// print the population of DR Congo
fmt.Println(top4AfricanCountriesPopulation["DR Congo"])
// output: 89561403

One thing to note though about the retrieval of data from a map is that if a key does not exist, the Go compiler will not consider that as an error because by design the Go compiler expects those kinds of things to occur. Another example would be when reading from a file if the supplied file does not exist, it will not flag that as an error. Alternatively, Go returns a flag alongside the value from the map, using which you can test if a key exists.

// using our African population map
// let's try to retrieve Kenya's population
fmt.Println(top4AfricanCountriesPopulation["Kenya"])
// output: 0
// by default Go gives a zero value to non-initialized variables
// let's use the flag to determine if a value exist in the map
key := "Kenya"
_, flag := top4AfricanCountriesPopulation[key]
fmt.Printf("does the key %v exist? %v", key, flag)

Practice with maps.

Structs

A struct is a grouping of related variables under one data structure. For more information, read this article.

// How to create a struct
type Person struct{
FirstName string
LastName string
Age int8
Hobbies []string
}
// How to use a struct
tado := Person{
FirstName: "twist",
LastName: "tado",
Age: 19,
Hobbies: []string{"coding", "writing", "playing football"},
}
// How to retrieve data from a struct
fmt.Println(tado.Age)

Go allows us to create anonymous structs. They are useful when you want to create a one-time usable structure. It is a mix of declaration and initialization, plus they can be used just like any other struct.

// anonymous struct
doctorJuly := struct{ name string} { name: "Juliette"}
// Print the doctor's name
fmt.Println(doctorJuly.name)

practice with struct.

Bonus

In Go, the way you name your variables matters a lot not just because it is case insensitive but also because if you start a variable name with an uppercase example Name:= “Micheal”, the Go compiler will make it available for use by any piece of code under the same package.

Go does not allow you to create a variable then not use it anywhere in the code, it will throw an error if it finds an unused variable in the code.

Constants

constants are inverse of variables. While variables can change after the declaration, constants remain the same throughout the life of the whole program. The value of a constant must be determined at compile time otherwise the Go compiler will throw an error.

Unlike variables, constants cannot use the := expression. The const is used instead of var.

const Pi = 3.14// this will throw an error
// because the Sqrt(4) cannot be determined at
// compile time
const sqrt4 = math.Sqrt(4)

Conclusion

We have seen how to declare variables using both primitives and collection data types. Do not forget, the naming of variables matters a lot as mentioned in the Bonus section. Constants are used to represent values that will not change thought out the life of the program. #HappyReading

--

--