Skip to main content

Golang Variables

·160 words·1 min·
Table of Contents
Lessons learned from `Learn Go with Tests` - This article is part of a series.
Part 5: This Article

Types
#

Golang lets you create new types from existing ones. This allows for neat stuff:

package main

import "fmt"

type Bitcoin int

func (b Bitcoin) String() string {
	return fmt.Sprintf("%d BTC", b)
}

func main() {
	b := Bitcoin(10)
	fmt.Println(b)
}
10 BTC

Maps
#

Maps are like associative arrays. When searching a map a second boolean variable is also returned to tell you if the key exists.

package main

import "fmt"

type Dictionary map[string]string

var dictionary = Dictionary{"test": "this is a test"}

func main() {
	foundWord, ok := dictionary["test"]
	notFoundWord, notOk := dictionary["tralala"]

	fmt.Println(fmt.Sprintf("%q | %t", foundWord, ok))
	fmt.Println(fmt.Sprintf("%q | %t", notFoundWord, notOk))
}
"this is a test" | true
"" | false

Golang includes a builtin map delete function to delete map elements.

package main

import "fmt"

type Dictionary map[string]string

var dictionary = Dictionary{
  "word1": "first word",
  "word2": "second word",
}

func main() {
  fmt.Println(fmt.Sprintf("%v", dictionary))
  delete(dictionary, "word1")
  fmt.Println(fmt.Sprintf("%v", dictionary))
}
map[word1:first word word2:second word]
map[word2:second word]
Lessons learned from `Learn Go with Tests` - This article is part of a series.
Part 5: This Article