UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ Lab 20

Before the lab

Read

Arrays

Time
25 minutes
Activity
Modify given example
// In Go, an _array_ is a numbered sequence of elements of a
// specific length. In typical Go code, [slices](slices) are
// much more common; arrays are useful in some special
// scenarios.

package main

import "fmt"

func main() {

	// Here we create an array `a` that will hold exactly
	// 5 `int`s. The type of elements and length are both
	// part of the array's type. By default an array is
	// zero-valued, which for `int`s means `0`s.
	var a [5]int
	fmt.Println("emp:", a)

	// We can set a value at an index using the
	// `array[index] = value` syntax, and get a value with
	// `array[index]`.
	a[4] = 100
	fmt.Println("set:", a)
	fmt.Println("get:", a[4])

	// The builtin `len` returns the length of an array.
	fmt.Println("len:", len(a))

	// Use this syntax to declare and initialize an array
	// in one line.
	b := [5]int{1, 2, 3, 4, 5}
	fmt.Println("dcl:", b)

	// You can also have the compiler count the number of
	// elements for you with `...`
	b = [...]int{1, 2, 3, 4, 5}
	fmt.Println("dcl:", b)

	// If you specify the index with `:`, the elements in
	// between will be zeroed.
	b = [...]int{100, 3: 400, 500}
	fmt.Println("idx:", b)

	// Array types are one-dimensional, but you can
	// compose types to build multi-dimensional data
	// structures.
	var twoD [2][3]int
	for i := range 2 {
		for j := range 3 {
			twoD[i][j] = i + j
		}
	}
	fmt.Println("2d: ", twoD)

	// You can create and initialize multi-dimensional
	// arrays at once too.
	twoD = [2][3]int{
		{1, 2, 3},
		{1, 2, 3},
	}
	fmt.Println("2d: ", twoD)
}
go run arrays.go
emp: [0 0 0 0 0]
set: [0 1 2 3 4]
get: 4
len: 5
dcl: [1 2 3 4 5]
dcl: [5 4 3 2 1]
idx: [100 0 0 0 400]
2d:  [[0 -1 -2] [1 0 -1]]
2d:  [[0 1 2] [0 1 2]]

Slices

Time
25 minutes
Activity
Modify given example
// _Slices_ are an important data type in Go, giving
// a more powerful interface to sequences than arrays.

package main

import (
	"fmt"
	"slices"
)

func main() {

	// Unlike arrays, slices are typed only by the
	// elements they contain (not the number of elements).
	// An uninitialized slice equals to nil and has
	// length 0.
	var s []string
	fmt.Println("uninit:", s, s == nil, len(s) == 0)

	// To create a slice with non-zero length, use
	// the builtin `make`. Here we make a slice of
	// `string`s of length `3` (initially zero-valued).
	// By default a new slice's capacity is equal to its
	// length; if we know the slice is going to grow ahead
	// of time, it's possible to pass a capacity explicitly
	// as an additional parameter to `make`.
	s = make([]string, 3)
	fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))

	// We can set and get just like with arrays.
	s[0] = "a"
	s[1] = "b"
	s[2] = "c"
	fmt.Println("set:", s)
	fmt.Println("get:", s[2])

	// `len` returns the length of the slice as expected.
	fmt.Println("len:", len(s))

	// In addition to these basic operations, slices
	// support several more that make them richer than
	// arrays. One is the builtin `append`, which
	// returns a slice containing one or more new values.
	// Note that we need to accept a return value from
	// `append` as we may get a new slice value.
	s = append(s, "d")
	s = append(s, "e", "f")
	fmt.Println("apd:", s)

	// Slices can also be `copy`'d. Here we create an
	// empty slice `c` of the same length as `s` and copy
	// into `c` from `s`.
	c := make([]string, len(s))
	copy(c, s)
	fmt.Println("cpy:", c)

	// Slices support a "slice" operator with the syntax
	// `slice[low:high]`. For example, this gets a slice
	// of the elements `s[2]`, `s[3]`, and `s[4]`.
	l := s[2:5]
	fmt.Println("sl1:", l)

	// This slices up to (but excluding) `s[5]`.
	l = s[:5]
	fmt.Println("sl2:", l)

	// And this slices up from (and including) `s[2]`.
	l = s[2:]
	fmt.Println("sl3:", l)

	// We can declare and initialize a variable for slice
	// in a single line as well.
	t := []string{"g", "h", "i"}
	fmt.Println("dcl:", t)

	// The `slices` package contains a number of useful
	// utility functions for slices.
	t2 := []string{"g", "h", "i"}
	if slices.Equal(t, t2) {
		fmt.Println("t == t2")
	}

	// Slices can be composed into multi-dimensional data
	// structures. The length of the inner slices can
	// vary, unlike with multi-dimensional arrays.
	twoD := make([][]int, 3)
	for i := range 3 {
		innerLen := i + 1
		twoD[i] = make([]int, innerLen)
		for j := range innerLen {
			twoD[i][j] = i + j
		}
	}
	fmt.Println("2d: ", twoD)
}
go run slices.go 
uninit: [] true true
emp: [a b c] len: 3 cap: 10
set: [a B c]
get: B
len: 3
apd: [a B c d e f]
cpy: [a B c d e f]
sl1: [c d]
sl2: [a B c d]
sl3: [d e f]
dcl: [g h i j]
2d:  [[0] [0 1] [0 1 2]]

Debugging

Time
10 minutes
Activity
Demo
$ setenv GOBIN $HOME/.local/bin ; go install github.com/go-delve/delve/cmd/dlv@latest
// Our first program will print the classic "hello world"
// message. Here's the full source code.
package main

import "fmt"

func main() {
	fmt.Println("hello world")
}
$ cd hello
$ go mod init example.com/main
$ dlv debug
Type 'help' for list of commands.
(dlv) b main.main
(dlv) continue
> [Breakpoint 1] main.main() ./hello-world.go:5 (hits goroutine(1):1 total:1) (PC: 0x4b63f3)
     1: package main
     2: 
     3: import "fmt"
     4: 
=>   5: func main() {
     6:     s:="world"
     7:     fmt.Println("hello "+s)
     8: }
(dlv) n
> main.main() ./hello-world.go:6 (PC: 0x4b63f7)
     1: package main
     2: 
     3: import "fmt"
     4: 
     5: func main() {
=>   6:     s:="world"
     7:     fmt.Println("hello "+s)
     8: }
(dlv) n
 main.main() ./hello-world.go:7 (PC: 0x4b640c)
     2: 
     3: import "fmt"
     4: 
     5: func main() {
     6:     s:="world"
=>   7:     fmt.Println("hello "+s)
     8: }
(dlv) p s
"world"
(dlv)

Merging sorted lists

Time
40 minutes
Activity
Debug complete program
package main

import "fmt"
import "slices"

func merge(A []int, B []int) []int {
    i,j,k  := 0,0,0;
    out := make([]int, len(A)+len(B));

    for (i < len(A) && j < len (B)) {
        if (A[j] < B[i]) {
            out[k] = A[i]
            i++
        } else {
            out[k] = B[j]
            j++
        }
        k++
    }
    for (i<len(A)) {
        out[k] = A[i]
        i++
        k++
    }
    for (j<len(B)) {
        out[k] = B[i]
        j++
        k++
    }
    return out;
}


func main() {
    A := []int{0,2,4,6,8};
    B := []int{1,3,5,7,9};
    expected := []int{0,1,2,3,4,5,6,7,8,9}
    out := merge(A,B);
    if slices.Equal(expected,out) {
        fmt.Println("SUCCESS")
    } else {
        fmt.Println("FAIL")
        fmt.Println(out)
    }
}