Back to home

PushPopUnshiftShift
Basic Slices with Golang main image

Basic Slices with Golang

Set up the folder with test and main file:

1 2 3 4 5 6 7 8 9 // slices_test.go package slices import ( "testing" ) // slices.go package slices

Push

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // slices_test.go func TestPushToIntSlice(t *testing.T) { s := []int{1, 2, 3} i := 4 exp := []int{1, 2, 3, 4} res := Push(s, i) for idx, val := range res { if exp[idx] != val { t.Fatalf("Expected %+v, got %+v", exp, res) } } } // Push append int to end of int slice func Push(a []int, b int) []int { return append(a, b) }

Pop

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // 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

1 2 3 4 5 6 // 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

1 2 3 4 5 6 7 // 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 }

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.