×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Change Elements of a Slice

Last Updated : May 04, 2025

Go slices elements can be directly changed by using index positions without creating a new slice.

Changing Slice Elements Using Index

You can modify a specific element in a slice by assigning a new value to its index.

Example

package main
import "fmt"

func main() {
    names := []string{"Amit", "Bhavna", "Chetan"}

    names[1] = "Divya" // Changing the second element

    fmt.Println("Updated names slice:", names)
}

When executed, this program outputs:

Updated names slice: [Amit Divya Chetan]

Changing Elements in a Loop

You can use a for loop to iterate through a slice and update elements based on a condition or logic.

Example

package main
import "fmt"

func main() {
    numbers := []int{10, 20, 30}

    for i := 0; i < len(numbers); i++ {
        numbers[i] = numbers[i] * 2 // Doubling each element
    }

    fmt.Println("Doubled numbers:", numbers)
}

When executed, this program outputs:

Doubled numbers: [20 40 60]

Changing Elements Using range

When using range to iterate over a slice, you receive a copy of each value, so modifying it directly doesn't change the original slice. To update elements, use the index returned by range.

Example

package main
import "fmt"

func main() {
    scores := []int{55, 65, 75}

    for i, _ := range scores {
        scores[i] += 5 // Adding 5 to each score
    }

    fmt.Println("Updated scores:", scores)
}

When executed, this program outputs:

Updated scores: [60 70 80]

Exercise

Select the correct option to complete each statement about modifying elements of a slice in Go.

  1. To change the value of an element at a specific index in a slice, use the syntax ___.
  2. Modifying a slice element directly affects the ___ it is derived from.
  3. To update multiple elements in a slice, you can use a ___.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.