How to remove last element of slice in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, we will learn to remove last element of slice in golang, here we will use len to get length, and fmt to print packages.

So, first, we will create the s variable and assign string slice data to it.

Second, we will check length of slice, and in the last step, we will remove last element.

Let’s dive into code.

package main

import "fmt"

func main() {
	s := []string{"Infinitbility", "aguidehub", "notebility"}

	if len(s) > 0 {
		s = s[:len(s)-1]
	}

	fmt.Println(s)
}

When you run it you will only first two elements, check in output console in following image.

remove, last element, golang

Try it yourself

All the best 👍

Follow me on Twitter