Skip to content
Your Name edited this page Nov 22, 2020 · 1 revision

Variables

const a = 123
const a int = 123

var x int = 5
x := 5

type myStruct struct {
	field1 int
	field2 string
}

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

Functions

With return types and typed params:

func name(astring string, reference *int, unsized_array []int, sized_array [10]int) int {
    return 10
}

Call:

name("abc", 1)

Arrays

new

Allocates memory and returns pointer to the new value

new(int)

Goroutines

go function1()

Loops

Classic for

for i := 0; i < 10; i++ {
		sum += i
}

Infinite for (forever)

for {
	
}

Break outer loop with a label

outer:
    for {
        select {
            case a:
                break outer
        }
    }

Int to string

import "strconv" s := strconv.Itoa(100)

Packages and imports

Imports

import (
    "path/to/a/package"
)

The path string specifies a location. The package "foo" lines in the .go files in this location determine the name of the package. By convention, the location name is the same as the package name, but it's not a requirement - the package name can be different from the last segment of the location path. All the .go files in this location have to specify the same package name.

Exports

The package exports all identifiers starting with a capital letter. They can be used this way: packagename.ExportedIdentifier(arg1, arg2).

Libraries

the Go stdlib (import "pkg") is declared to be stable. The packages from golang.org/x/* are also officially developed, but there are less strict backward-compatibility rules.

Snippets

Reading files

import "io/ioutil"
dat, err := ioutil.ReadFile("/tmp/dat")

Loading YAML

func loadConfig() *Config {
	data, err := ioutil.ReadFile("config.yaml")
	fmt.Printf("%s", data)
	if err != nil {

	}
	c := Config{}
	err = yaml.Unmarshal(data, &c)
	fmt.Println(c.DataDir)
	if err != nil {
	}
	return &c
}

Clone this wiki locally