Golang

Write an awesome doc for Golang.

View on GitHub

Install Go

# Manjaro linux
sudo pacman -Syu go

Structure of Go Code

go mod init github.com/kasir-barati/golang

[!TIP]

The name of module usually is the URL of a GitHub repository. But we can use any name we want, i.e. git mod init test.

go mod init result is a go.mod file

Now you can start creating new packages:

code src/utils/main.go

Now it’s time to build and run the program:

go build src/utils/main.go

Now let’s run the program:

./main

[!TIP]

You can also run the program with the go run src/utils/main.go command.

Variables & Constants

var name string = "John"

[!TIP]

We must use every variable we define, otherwise the compiler will throw an error.

Variable Types
int, uint int8, uint8 int16, uint16 int32, uint32 int64, uint64
- - - float32 float64
string - - - -
rune - - - -
bool - - - -

[!TIP]

Overflow:

The size of the variable matters and in runtime you might run into the issue of overflow.

var score int16 = 32767
score++
println(score) // -32768
var avg float32 = 999999.99
fmt.Println(avg) // 1e+06

[!NOTE]

len VS utf8.RuneCountInString:

len of a string is the number of bytes, NOT the number of characters!

var name string = "Öl"
println(len(name)) // 3

To get the number of characters we can use the utf8 package.

import "unicode/utf8"
var name string = "Öl"
println(utf8.RuneCountInString(name)) // 2

[!NOTE]

const is immutable & they must be initialized at declaration.

Functions

package main

import (
	"fmt"
)

func main() {
	var num1 int = 11
	var num2 int = 20
	var result int = add(num1, num2)
	fmt.Println(result)
}

func add(num1 int, num2 int) int {
	return num1 + num2
}
func divide(numerator int, denominator int) (int, int) {
  var result int = numerator / denominator
  var remainder int = numerator % denominator
  return result, remainder
}

[!TIP]

A common pattern in Go is to return an error as the last value:

import "errors"
func divide(numerator int, denominator int) (int, int, error) {
  if denominator == 0 {
     return 0, 0, errors.New("cannot divide by zero")
  }
  var result int = numerator / denominator
  var remainder int = numerator % denominator
  return result, remainder, nil
}

var divisionResult, divisionRemainder, error = divide(num1, num2)
if error != nil {
  fmt.Println(error.Error())
  return
}

Logical Operators & Comparison Operators

== != && || > <
if res == 10 { if err != nil { if num2 > 0 && num1 > 0 { if res == 2 || res == 4 { if num1 > 0 { if num2 < 0 {

[!NOTE]

  • If the first statement in an if statement is true, the second statement is NOT evaluated for the || operator.
  • If the first statement in an if statement is false, the second statement is NOT evaluated for the && operator.

switch Statement

var num int = 10
switch num {
  case 1, 2:
    println("num is 1 or 2")
  case 10:
    println("num is 10")
  case 20:
    println("num is 20")
  default:
    println("num is not 10 or 20")
)
switch {
  case num > 0:
    println("num is positive")
  // ...
}

Arrays

import "fmt"

var scores [5]int = [5]int{1, 2, 3, 4, 5}
fmt.Println(scores[:])   // [0 0 0 0 0]
fmt.Println(scores[1:3]) // [2 3]

[!TIP]

scores := [...]int{1, 2, 3, 4, 5}
var names [3]string

Slices

var scores []int
scores = append(scores, 1)

[!TIP]

Use speared operator to append a list of values to a slice:

numbers := []int{1, 2, 3, 4, 5}
scores = append(scores, numbers...)

make Function

var scores []int = make([]int, 5, 10)