Basic Slices with Golang
Published: Feb 25, 2019
Last updated: Feb 25, 2019
Set up the folder with test and main file:
1// slices_test.go2package slices34import (5 "testing"6)78// slices.go9package slices
Push
1// slices_test.go2func TestPushToIntSlice(t *testing.T) {3 s := []int{1, 2, 3}4 i := 456 exp := []int{1, 2, 3, 4}7 res := Push(s, i)8 for idx, val := range res {9 if exp[idx] != val {10 t.Fatalf("Expected %+v, got %+v", exp, res)11 }12 }13}1415// Push append int to end of int slice16func Push(a []int, b int) []int {17 return append(a, b)18}
Pop
// slices_test.go func TestPopIntFromSliceSlice(t *testing.T) { s := []int{1, 2, 3, 4} expArr := []int{1, 2, 3} exp := 4 res, resArr := Pop(s) for idx, val := range resArr { if expArr[idx] != val { t.Fatalf("Expected %+v, got %+v", exp, res) } } if exp != res { t.Fatalf("Popped integer not as expected") } } // Pop return an integer from an array + array without last index func Pop(a []int) (int, []int) { x, b := a[len(a)-1], a[:len(a)-1] return x, b }
Unshift
// slices_test.go // Unshift append as first element and return new slice func Unshift(a []int, b int) []int { return append([]int{b}, a...) }
Shift
// slices_test.go // Shift remove from front and return int and new slice func Shift(a []int) (int, []int) { x, b := a[0], a[1:] return x, b }
Basic Slices with Golang
Introduction