Range

Reading material

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


First exercise


// range1
// Make me compile!
//
// I AM NOT DONE
package main

import "fmt"

func main() {
	evenNumbers := []int{2, 4, 6, 8, 10}

	for _, v := {
		fmt.Printf("%d is even\n", v)
	}
}

Second exercise


// range2
// Make me compile!
//
// I AM NOT DONE
package main

import "fmt"

func main() {
	phoneBook := map[string]string{
		"Ana":  "+01 101 102",
		"John": "+01 333 666",
	}

	for name, phone := range phoneBook {
		fmt.Printf("%s has the %s phone\n", name, phone)
	}
}

Third exercise


// range3
// Make me compile!
//
// I AM NOT DONE
package main_test

import (
	"reflect"
	"testing"
)

func TestFilterEvenNumbers(t *testing.T) {
	numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

	evenNumbers := []int{} // use range to filter even numbers

	for range numbers {
	}

	if !reflect.DeepEqual(evenNumbers, []int{2, 4, 6, 8, 10}) {
		t.Errorf("evenNumbers does not contain all the required even numbers, got %v", evenNumbers)
	}
}


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