Slices

Reading material

A Tour of Go: Slices. Go by Example: Slices.


First exercise


// slices1
// Make me compile!

// I AM NOT DONE
package main

import "fmt"

func main() {
	a := make(, 3, 10) // play with length and capacity
	fmt.Println("length of 'a':", len(a))
	fmt.Println("capacity of 'a':", cap(a))
}

Second exercise


// slices2
// Make me compile!

// I AM NOT DONE
package main

import "fmt"

func main() {
	names := [4]string{"John", "Maria", "Carl", "Peter"}
	lastTwoNames := names[] // after figuring out the answer, try with other low/high bounds
	fmt.Println(lastTwoNames)
}

Third exercise


// slices3
// Make me compile!

// I AM NOT DONE
package main

import "fmt"

func main() {
	names := []string{"John", "Maria", "Carl", "Peter"}
	names = append()
	fmt.Println(names)
}

Fourth exercise


// slices4
// Make me compile!

// I AM NOT DONE
package main_test

import (
	"reflect"
	"testing"
)

func TestGetOnlyFirstName(t *testing.T) {
	names := []string{"John", "Maria", "Carl", "Peter"}
	firstName := names[3]

	if firstName != "John" {
		t.Errorf("firstName value must be John")
	}
}

func TestGetFirstTwoNames(t *testing.T) {
	names := []string{"John", "Maria", "Carl", "Peter"}
	firstTwoNames := names[5:10]
	expectedFirstTwoNames := []string{"John", "Maria"}

	if !reflect.DeepEqual(firstTwoNames, expectedFirstTwoNames) {
		t.Errorf("firstTwoNames should be %v, but got %v", expectedFirstTwoNames, firstTwoNames)
	}
}

func TestGetLastTwoNames(t *testing.T) {
	names := []string{"John", "Maria", "Carl", "Peter"}
	lastTwoNames := names[5:10]
	expectedLastTwoNames := []string{"Carl", "Peter"}

	if !reflect.DeepEqual(lastTwoNames, expectedLastTwoNames) {
		t.Errorf("firstTwoNames should be %v, but got %v", expectedLastTwoNames, lastTwoNames)
	}
}


If something is wrong in this page, edit this page on GitHub