Variables | Go

Constants#

Constants are defined like so

const englishHelloPrefix = "Hello, "
func Hello(name string) string {
return englishHelloPrefix + name
}

Constants should improve performance of your application as it saves you creating the "Hello, " string instance every time Hello is called.

same type variables#

var a, b int
func addr(x, y int) int {
return x + y
}

Arrays and Slices#

Array#

We can initialize an array in two ways:

  • [N]type{value1, value2, ..., valueN} e.g. numbers := [5]int{1, 2, 3, 4, 5}
  • [...]type{value1, value2, ..., valueN} e.g. numbers := [...]int{1, 2, 3, 4, 5}

Slice#

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

Capacity and append#

If you have a slice with a capacity of 2 and try to do mySlice[10] = 1 you will get a runtime error. So we should make to create a slice with capacity

However, we can use the append function which takes a slice and a new value, returning a new slice with all the items in it.

Slice of slice#

tail := numbers[1:]
head := numbers[:1]
part := numbers[2:4]
var sums []int
for _, numbers := range numbersToSum {
sums = append(sums, Sum(numbers))
}

Range#

Arrays#

for _, number := range numbers { }

range lets you iterate over an array. Every time it is called it returns two values, the index and the value. We are choosing to ignore the index value by using _ blank identifier.

Variadic Functions#

can take a variable number of arguments

func SumAll(numbersToSum ...[]int) (sums []int) {
return
}

DeepEqual#

Go does not let you use equality operators with slices. You could write a function to iterate over each got and want slice and check their values but for convenience sake, we can use [reflect.DeepEqual][deepEqual] which is useful for seeing if any two variables are the same.

func TestSumAll(t *testing.T) {
got := SumAll([]int{1, 2}, []int{0, 9})
want := []int{3, 9}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v want %v", got, want)
}
}

(make sure you import reflect in the top of your file to have access to DeepEqual)

It's important to note that reflect.DeepEqual is not "type safe", the code will compile even if you did something a bit silly.

make#

make allows you to create a slice with a starting capacity of the len (2nd argument) x := make([]int, 2)

Methods#

It is a convention in Go to have the receiver variable be the first letter of the type. r Rectangle

Interfaces#

Decoupling#

func TestArea(t *testing.T) {
checkArea := func(t *testing.T, shape Shape, want float64) {
t.Helper()
got := shape.Area()
if got != want {
t.Errorf("got %g want %g", got, want)
}
}
t.Run("rectangles", func(t *testing.T) {
rectangle := Rectangle{12, 6}
checkArea(t, rectangle, 72.0)
})
t.Run("circles", func(t *testing.T) {
circle := Circle{10}
checkArea(t, circle, 314.1592653589793)
})
}

Notice how our helper does not need to concern itself with whether the shape is a Rectangle or a Circle or a Triangle. By declaring an interface the helper is decoupled from the concrete types and just has the method it needs to do its job.

This kind of approach of using interfaces to declare only what you need is very important in software design and will be covered in more detail in later sections.

Struct#

The %#v format string#

will print out our struct with the values in its field, so the developer can see at a glance the properties that are being tested.

Create new types from existing ones#

  • Useful for adding more domain specific meaning to values
  • Can let you implement interface
type Bitcoin int
type Wallet struct {
balance: Bitcoin
}

To make Bitcoin you just use the syntax Bitcoin(999).

Anonymous struct#

areaTests := []struct {
shape Shape
want float64
}{
{Rectangle{12, 6}, 72.0},
{Circle{10}, 314.1592653589793},
}

Map#

Definition#

map lookup can return 2 values. The second value is a boolean which indicates if the key was found successfully.

var ErrNotFound = errors.New("could not find the word you were looking for")
dictionary := map[string]string{"test": "this is just a test"}
dictionary["test2"] = "value"
delete(dictionary, "test2")
func Search(d map[string]string, word string) (string, error) {
definition, ok := d[word]
if !ok {
return "", ErrNotFound
}
return definition, nil
}

Reference Types#

An interesting property of maps is that you can modify them without passing them as a pointer. This is because map is a reference type. Meaning it holds a reference to the underlying data structure, much like a pointer. The underlying data structure is a hash table, or hash map, and you can read more about hash tables here.

Maps being a reference is really good, because no matter how big a map gets there will only be one copy.

Map with nil value#

A gotcha that reference types introduce is that maps can be a nil value. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic. You can read more about maps here.

Therefore, you should never initialize an empty map variable:

var m map[string]string

Instead, you can initialize an empty map like we were doing above, or use the make keyword to create a map for you:

var dictionary = map[string]string{}
// OR
var dictionary = make(map[string]string)

Both approaches create an empty hash map and point dictionary at it. Which ensures that you will never get a runtime panic.