当在Go中传递给函数时,为什么Slices内部结构会“被引用传递”?

package main

import "fmt"

func main() {

    a := SomeType{myslice: []int{1, 2, 3}, decimal: 2.33}

    for _, i := range a.myslice {
        fmt.Println(i)
    }
    fmt.Println(a.decimal)

    addOne(a)

    for _, i := range a.myslice {
        fmt.Println(i)
    }
    fmt.Println(a.decimal)

}

type SomeType struct {
    myslice []int
    decimal float32
}

func addOne(s SomeType) {
    s.myslice[0]++
    s.decimal += 1.2
}

The output for the code above is:

1 2 3 2.33 2 2 3 2.33

Even though i have not passed the SomeType object a by reference the myslice field is being modified in the original object. Why is this happening? Is there anyway to pass the entire object by value without having to create a copy of the original object?

The slice is not really being passed by reference; if you append to it in addOne, its length will not change. But a slice contains a reference (or pointer) to its backing array. So when you copy a slice, the new one shares the same backing array with the old one.

The fact that the slice is inside a struct doesn't make any difference. You would see the same thing if you changed addOne to just take a slice instead of the whole struct.