Back to home

Basic Slices with Golang

Published: Feb 25, 2019

Last updated: Feb 25, 2019

    Set up the folder with test and main file:

    // slices_test.go package slices import ( "testing" ) // slices.go package slices

    Push

    // 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

    // 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 }

    Personal image

    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 Visibuild.

    1,200+ PEOPLE ALREADY JOINED ❤️️

    Get fresh posts + news direct to your inbox.

    No spam. We only send you relevant content.

    Basic Slices with Golang

    Introduction

    Share this post