0
package main

import "fmt"

func main() {
    ages := make([]int, 3, 7)
    fmt.Printf("original slice memory address is %p\n", ages)
    modify(ages)
    fmt.Println(ages)
}
func modify(ages []int) {
    fmt.Printf("inside function the address of slice is %p\n", ages)
    ages[0] = 1
    ages = append(ages, 1)
    fmt.Printf(" after append address  %p\n", ages)
    fmt.Printf("after append value %v\n", ages)
}

the result is :

original slice memory address is 0xc0000ac040

inside the function the address of slice is 0xc0000ac040

after append address 0xc0000ac040

after append value [1 0 0 1]

[1 0 0]


I'm wondering why the address is the same. But it still doesn't change the value of the slice.

I've read some articles said it manipulate the copy of the ages, not the "real" ages. And I also know that I can pass *ages to the function. And it works.


I just can't understand the address is the same. But the behavior is different.

xinlei si
  • 19
  • 4
  • Slices are small struct-like data structures that point to a backing array that stores the elements. `append()` writes new elements to that array if there's room, else it allocates a new. `append()` also returns the new slice header which may or may not point to the same array. – icza Oct 28 '20 at 08:11
  • 1
    Please read blog posts about slices: [Go Slices: usage and internals](https://blog.golang.org/slices-intro); and [Arrays, slices (and strings): The mechanics of 'append'](https://blog.golang.org/slices). – icza Oct 28 '20 at 08:12
  • If you want ages is modified after passing to function, you can use pointer to slice. Great explanation can found here: https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b – Tino Oct 28 '20 at 09:02

0 Answers0