Fundamentals 9 min read

Master Go Slices: From Basics to Advanced Operations

This article introduces Go slices, explaining why they’re needed, how they differ from arrays, their memory layout, and demonstrates declaration, creation with make, slicing arrays, appending, modifying, deleting, and iterating over elements with clear code examples.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Go Slices: From Basics to Advanced Operations

Continuing Go Basics: Slices

In the previous article we covered Go variables. This article continues the Go fundamentals by focusing on slices, a flexible, dynamically-sized sequence type.

Why Use Slices?

Arrays have a fixed length and cannot be expanded. When you need to store more elements than an array’s capacity, you must use a slice.

package main
import "fmt"
func main() {
    var studentList = [4]string{"张三", "李四", "王五", "小刘"}
    fmt.Println(studentList)
}

The above code defines an array of four strings. Adding a fifth element would cause an out‑of‑bounds error.

package main
import "fmt"
func main() {
    // Attempt to add a fifth element – will cause an error
    var studentList = [4]string{"张三", "李四", "王五", "小刘"}
    // studentList[4] = "小七" // invalid array index 4 (out of bounds for 4‑element array)
    fmt.Println(studentList)
}

Conclusion: arrays have a fixed length and cannot be appended to; attempting to do so results in a runtime error.

Slices

In other languages slices are known as lists (Python, Java, PHP). In Go they are called slices . Slices are a general‑purpose storage structure that resides in heap memory.

Slice memory layout
Slice memory layout

Verifying Slice Memory Allocation

package main
import "fmt"
func main() {
    var studentList = []string{"张三", "李四"}          // slice (no length specified)
    var studentList2 = [3]string{"张三", "李四", "王五"} // array (length specified)
    fmt.Printf("%p
", studentList)   // prints address (heap allocation)
    fmt.Printf("%p
", studentList2) // prints !%p because array is on stack
}

Printing a slice with %p shows its heap address, while an array prints %!p because it resides on the stack.

Using Slices

A slice is a reference type stored on the heap and contains three fields: address, length, and capacity. It is ideal for quickly operating on a collection of data.

Declaring a Slice

Syntax:

var variableName []ElementType
// Example:
package main
func main() {
    var studentList []string
    var studentList2 []int
    var studentList3 []float64
    var studentList4 = []string{} // type inference with empty literal
}

Creating a Slice with make

var variableName = make([]ElementType, length, capacity)
// Example:
package main
import "fmt"
func main() {
    var studentList = make([]int, 10, 20)
    fmt.Println(studentList) // [0 0 0 0 0 0 0 0 0 0]
}

Slice from an Array

package main
import "fmt"
func main() {
    var nameArray = [5]int{1, 2, 3, 4, 5}
    var nameSlice = nameArray[1:3] // result is a slice
    fmt.Printf("%T %T
", nameArray, nameSlice)
}

Note: slicing an array using [start:end] returns a slice that includes the start index but excludes the end index ("left‑inclusive, right‑exclusive").

Appending Elements (Add)

In Go, use append to add elements to a slice.

package main
import "fmt"
func main() {
    var studentList []string
    studentList = append(studentList, "张三")
    studentList = append(studentList, "李四")
    studentList = append(studentList, "王五")
    fmt.Println(studentList)
}

After calling append, assign the result back to the original slice variable.

Appending Multiple Elements at Once

package main
import "fmt"
func main() {
    var list1 = []string{"张三", "李四", "王五", "小刘"}
    var list2 = make([]string, 10)
    list2 = append(list2, "八神")
    list2 = append(list2, "八神", "九尾")
    list2 = append(list2, list1...)
    fmt.Println(list2)
}

Modifying Elements (Update)

package main
import "fmt"
func main() {
    var names = []string{"张三", "李四"}
    names[1] = "李四666"
    fmt.Println(names) // [张三 李四666]
}

Deleting Elements (Remove)

Go does not provide a direct delete operation for slices; you can remove an element by re‑slicing and appending.

package main
import "fmt"
func main() {
    var names = []string{"张三", "李四", "王五", "小刘", "七阿"}
    // Remove element at index 2 ("王五")
    names = append(names[:2], names[3:]...)
    fmt.Println(names) // [张三 李四 小刘 七阿]
}

Iterating Over a Slice (Read)

package main
import "fmt"
func main() {
    var names = []string{"张三", "李四", "王五", "小刘", "七阿"}
    // Standard for loop
    for i := 0; i < len(names); i++ {
        fmt.Println(names[i])
    }
    // Range loop
    for index, value := range names {
        fmt.Println(index, value)
    }
}

Summary

This article covered Go slices, including their declaration, creation with make, slicing from arrays, appending, updating, deleting, and iterating. If you have questions, feel free to leave a comment in the discussion area.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Goslices
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.