Getting Started with Go: Basics

Mike Dyne
Evendyne
Published in
7 min readDec 19, 2022

In this article, we’ll cover the basics of Go, including its syntax, basic data types, control structures, and functions. By the end of this tutorial, you’ll have a solid foundation in Go and be ready to explore more concepts in future articles.

Golang’s syntax

Go, also known as Golang, was developed by Google as an open-source programming language. It was designed to be easy to learn and use, with a focus on simplicity and readability. Go is a statically-typed language, meaning that variables must be declared with a specific type, such as string or int, before they can be used. This can help catch errors early on and make the code more reliable.

Syntax

Let’s dive into the syntax of Go. Go uses curly braces to enclose blocks of code, and lines are not terminated with a semicolon. Here’s a simple example that prints “Hello, World!” to the console:

package main

import "fmt"

func main() {
fmt.Println("Hello, 世界!")
}

In this example, we have a package called main, which is a special package in Go that defines the entry point for the program. The import statement allows us to use functions from other packages, in this case the fmt package which provides input/output functions. The main function is the starting point for the program and contains the code that we want to execute. The fmt.Println function is used to print a string to the console.

We can also use the import statement to import multiple packages in a single line:

import (
"fmt"
"math"
)

Data Types

Go has a number of built-in data types, including integers, floating-point numbers, and strings. Here’s an example of how to declare and initialize variables:

var i int = 42
var f float64 = 3.14
var s string = "Hello, Go!"
var b bool = true

We can also use short variable declarations to declare and initialize variables in a single line:

i := 42
f := 3.14
s := "Hello, Go!"
b := true

In Go, a const is a variable that cannot be modified after it has been assigned a value. Constants are used to define values that are fixed and unchanging, such as mathematical constants or physical constants.

Here’s an example of how to declare and initialize a constant in Go:

const pi = 3.14159265

Go also supports arrays and slices, which are ordered collections of values. Here’s an example of how to declare and initialize an array:

var a [3]int = [3]int{1, 2, 3}

Slices are similar to arrays, but they can grow and shrink as needed. Here’s how to declare and initialize a slice:

s := []int{1, 2, 3}

To append an element to the end of an array or slice, you can use the append function. For example:

var arr [5]int
// Append the value 10 to the end of the array
arr = append(arr, 10)

To remove an element from an array, you will need to create a new array without the element you want to remove, as there is no built-in function for that. Here is an example:

arr := [5]int{1, 2, 3, 4, 5}
// Create a new array without the element at index 2
newArr := append(arr[:2], arr[3:]...)
fmt.Println(newArr) // Output: [1 2 4 5]

Control Structures

Go has a number of control structures for controlling the flow of a program. The if statement allows us to execute a block of code if a condition is true:

if x > 0 {
fmt.Println("x is positive")
}

We can also use an else clause to execute a different block of code if the condition is false:

if x > 0 {
fmt.Println("x is positive")
} else {
fmt.Println("x is not positive")
}

Go also has a switch statement that allows us to test multiple conditions and execute different blocks of code depending on the result. Here’s how to use a switch statement:

switch x {
case 1:
fmt.Println("x is 1")
case 2:
fmt.Println("x is 2")
default:
fmt.Println("x is not 1 or 2")
}

In this snippet, the switch statement will test the value of x and execute the appropriate block of code. If x is 1, it will print “x is 1”. If x is 2, it will print “x is 2”. If x is neither 1 nor 2, it will print “x is not 1 or 2”.

Go has several variations of the for loop. The classic version of for allows us to execute a block of code multiple times. Here’s an example of how to use a for loop:

for i := 0; i < 10; i++ {
fmt.Println(i)
}

In this example, the for loop will iterate 10 times, starting at 0 and ending at 9. On each iteration, it will print the current value of i to the console.

Another version is the range loop, which allows us to iterate over the elements of an array, slice, string, or other collection:

a := [3]int{1, 2, 3}

for i, v := range a {
fmt.Printf("index %d, value %d\n", i, v)
}

Here the for range loop will iterate over each element in the a array, and on each iteration it will assign the current index to the variable i and the current value to the variable v. It will then print the index and value to the console.

The for range loop is a convenient way to iterate over the elements of a collection and perform an action on each element. It’s particularly useful for working with slices and strings, as it allows us to easily access both the index and the value of each element.

Keep in mind that the for range loop is a read-only loop, meaning that we cannot modify the elements of the collection within the loop. If we need to modify the elements of a collection, we can use a regular for loop or the index and value assignment syntax to access and modify the elements directly. More on this in a later article.

Another variation of the for loop is the empty for loop, which has no initializer, condition, or increment statement. The empty for loop is often used as an infinite loop, because it has no exit condition. Here's an example of an empty for loop:

for {
fmt.Println("Enter a number:")
var n int
fmt.Scanln(&n)
if n == 0 {
break
}
fmt.Println("You entered:", n)
}

In the example, the for loop will run indefinitely, prompting the user to enter a number on each iteration. If the user enters 0, the break statement will be executed, and the loop will be exited. If the user enters a non-zero number, the loop will continue and print the entered number to the console.

It’s also possible to use the continue statement to skip the remaining statements in the current iteration of the loop and continue with the next iteration. Here's an example of how to use the continue statement:

for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}

fmt.Println(i)
}

On each iteration, the if statement will test whether the current value of i is even. If it is, the continue statement will be executed, and the remaining statements in the loop will be skipped.

Functions

Functions are an essential part of Go and are used to organize and reuse code. In Go, a function is a block of code that performs a specific task and can be called from other parts of the program. Here’s an example of a simple function that adds two integers and returns the result:

func add(x int, y int) int {
return x + y
}

We can call the add function like this:

result := add(1, 2)

In this snippet, the add function will be called with the arguments 1 and 2, and the result will be stored in the variable result.

Go allows us to define functions with multiple parameters of the same type by using type inference. For example, we can rewrite the add function like this:

func add(x, y int) int {
return x + y
}

In this version of the add function, we can omit the type of the x and y parameters, because Go can infer their type from the type of the return value.

Go also allows us to return multiple values from a function using a tuple. Here’s an example of a function that returns both the sum and the difference of two integers:

func sumAndDiff(x, y int) (int, int) {
return x + y, x - y
}

We can call this function and assign the returned values to variables like this:

sum, diff := sumAndDiff(1, 2)

Go functions can also have named return values, which can make the code easier to read and understand. Here’s an example of a function with named return values:

func sumAndDiff(x, y int) (sum int, diff int) {
sum = x + y
diff = x - y
return
}

In this version of the sumAndDiff function, we have defined the sum and diff variables as the return values of the function. When we call the function and assign the returned values to variables, Go will automatically assign the values to the corresponding variables.

Functions in Go can also have variadic parameters, which allow them to accept a variable number of arguments. To define a variadic parameter, we use the ... syntax followed by the type of the parameter. Here's an example of a function that calculates the sum of a variable number of integers:

func sum(numbers ...int) int {
result := 0
for _, n := range numbers {
result += n
}
return result
}

In this example, the sum function has a variadic parameter numbers of type int. When we call the function, we can pass as many integers as we want, and Go will create a slice with all the arguments and assign it to the numbers parameter.

That’s A Wrap

That is a brief overview of some of the basic concepts in Go. In the next article, we’ll explore more topics such as structs, pointers and interfaces.

You can find more about Evendyne here.

--

--

Mike Dyne
Evendyne

I write articles in various software engineering topics. Read every story from me by subscribing here: https://medium.com/@mikedyne/membership