Need help regarding the slice and append

package main

import “fmt”

func modifyNums(nums []int) {
nums = append(nums, 100)
}

func main() {
nums := []int{1,2,3}

modifyNums(nums)
fmt.Println(nums)

}

This code above, i can understand that slice length is increased on demand actually the compiler expands the underneath array so the appended value is not displayed in the main function.
The only way to append 100 is pass by pointer or return the slice and reassign so its reflected in main()

Why is way to get this reflected in main function other than above two ways ?
Maybe i am missing to understand something ? Can someone help and clarify please ?

This is because every-time when slice is being appended/modified, a new slice is created as intended. Since the append operation is in different memory space (inside a different function), it didn’t update the intended memory space (in main()).

Read:

  1. Go Slices: usage and internals - The Go Programming Language
  2. Effective Go - The Go Programming Language
  3. Effective Go - The Go Programming Language

There are 2 ways to do it:

  1. Passing in as a memory pointer and then let the function update it accordingly (my preferred way as the function is self-explanatory sharply that it only updates existing memory).
  2. returning the slice as a result and then update the slice in main().

For method 2, here is the code:

package main

import "fmt"

func modifyNums(nums []int) []int {
	return append(nums, 100)
}

func main() {
	nums := []int{1, 2, 3}

	nums = modifyNums(nums)
	
	fmt.Println(nums)
}

UPDATE:

For Method 1 using pointer for this particular function:

package main

import "fmt"

func modifyNums(nums *[]int) {
	*nums = append(*nums, 100)
}

func main() {
	nums := []int{1, 2, 3}

	modifyNums(&nums)
	
	fmt.Println(nums)
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.