Get Started With Golang
By: The Educative Team
Tags: DevOps, Software Development, Programming, Go, Golang

Intermediate Concepts of Go

Control structures

Control structures are similar to that of C, but they’re generally simpler and flexible. There are no do or while loop. Instead, Go uses flexible for and switch loops.

There are also new control structures, such as a type switch and select . We do not use parentheses and the bodies are brace-delimited. Let’s take a deeper look at Go control structures.

if-else : This construct tests for a conditional statement, either logical or boolean. If a statement is true , the body between the { } is executed. If it’s false , the statements are ignored, and the statement after the if is executed. Keep in mind that the braces are mandatory even if there is only one statement in the body.

switch-case : This structure is used instead of long if statements that compare variables to values. This statement makes it easy to transfer-flow of execution in your code.

switch is generally more flexible than other languages. It takes this general form:

switch var1 {

case val1:

...

case val2:

...

default:

...

}

Like the if construct, a switch can also contain an initialization statement:

switch initialization; {

case val1:

...

case val2:

...

default:

...

}

select : this statement means we can wait on multiple channel operations, which we’ll discuss more later.

for-range : in Go, this statement allows us to iterate over an expression that evaluates to an array, slice, map, string, or channel. The basic syntax is below:

for index, value := range mydatastructure {

fmt.Println(value)

}

index : the index of the value we want to access.

: the index of the value we want to access. value : the value on each iteration.

: the value on each iteration. mydatastructure : holds the data structure whose values we are accessing in the loop.

Keep in mind that this example is a generalization. To learn more about case-by-case examples, take a look at the EdPresso shot on the for-range loop here.

Functions

Functions are the basic building blocks of Golang, as it shares many features of functional languages. As I mentioned before, functions are data since they have values and types. A Go program is built up of several functions. It’s best to start with the main( ) function and write them in calling, or logical, order.

Functions break down problems into smaller tasks and enable us to reuse code. There are three types of functions in Go, all of which end when they have executed their last statement before } or when it executes a return statement:

Normal functions that use an identifier

Anonymous or lambda functions

Methods

We write functions using this syntax:

func g() { // VALID

...

}

And we call them with this general format:

pack1.Function(arg1,arg2,...,argn)

Here function is a function in pack1 , and arg1 is the argument. When we invoke a function, it makes copies of the arguments, which are passed to the called function.

Let’s take a look at an example of a function to see Go in action. Here, we will dive into the printf( ) function in Golang. The print function allows you to print formatted data. It takes a template string that contains the text we will format and some annotation verbs that tell the fmt functions how to format.

fmt.printf("Sample template string %s",Object arg(s))

Conversion characters tell Golang how to format the data types. Some common specifiers are:

v — formats the value in a default format

d — formats decimal integers

g — formats the floating-point numbers

b — formats base 2 numbers

Say we wanted to print a string. The %s conversation character can be used in the template string to print string values. Look at the code below.

There are many other cases where we can use the print function. To see more, take a look at the EdPresso shot on the Golang print function.

package main

import "fmt" func main() {

var mystring = "Hello world"

fmt.Printf("The string is %s", mystring)

}

Output: The string is Hello World

Maps

Maps, also called hashes or dicts in other programming languages, are a built-in data type in Go. The name explains their purpose: a map maps keys to values. Think of a map as a way to store key-value pairs.

You can use these for fast lookups, retrievals, or deletion of data based on keys.

We declare a map using the following syntax:

var m map[KeyType]ValueType

m is the name of the map variable.

is the name of the map variable. KeyType is the option data type of the keys in the map. This can also be declared at the time of initialization.

is the option data type of the keys in the map. This can also be declared at the time of initialization. ValueType is the data type of the value in the key-value pairs.

The length of a map doesn’t need to be known at declaration, so it can grow dynamically. The value of an uninitialized map is nil .

Let’s look at a specific example of a map in Golang to see how they are made:

Output:

Map literal at “one” is: 1

Map created at “key2” is: 3.141590

Map assigned at “two” is: 3

Map literal at “ten” is: 0

Arrays and slices

Arrays in Go are similar to Python, but they aren’t very common in Go code because they’re inflexible and have a fixed size. Instead, slices are far more common and provide greater power. Slices in Go build off arrays, since they’re an abstraction of Go’s array type.

To declare an array, we use the following syntax:

var identifier [len]type

An array is fixed in size since its length is part of its type. For example, [5]int represents an array of five integers. A slice allows us to overcome some of the challenges of arrays and work with sequences of typed data without using additional memory.

A slice is a reference to a continuous section of an array, called the underlying array. A slice is dynamically sized and flexible. It’s formed when we specify two indices, separated by a colon. We use the type specification [ ]T . T is the type of elements in the slice. We declare a slice using the following syntax:

letters := []string{"a", "b", "c", "d"}

To declare the type for a variable with a slice, we use [ ] with the type of elements for the slice:

A slice, unlike an array, can change during execution. Additionally, slices come with the built-in append , which can return a slice that contains one or more new values. The syntax of the append method is:

slice = append(slice, elem1, elem2, ...)

Take a look at how it’s done:

Output:

length=0 capacity=0 []

length=1 capacity=1 [0]

length=2 capacity=2 [0 1]

length=5 capacity=6 [0 1 2 3 4]

Now that we have a sense of some of the intermediate Go concepts, let’s move on to some of the advanced things that Golang brings to the table. Keep in mind that there’s a lot more to learn. Some other intermediate concepts include: