切片是否按值传递?

问题描述 投票:0回答:5

在 Go 中,我正在尝试为我的旅行商问题制作一个争夺切片功能。在这样做的时候,我注意到当我开始编辑切片时,我每次传入的打乱函数都是不同的。

经过一些调试,我发现这是由于我在函数内部编辑了切片。但既然 Go 应该是一种“按值传递”的语言,这怎么可能呢?

https://play.golang.org/p/mMivoH0TuV

我提供了一个 playground 链接来说明我的意思。 通过删除第 27 行,您会得到与保留它不同的输出,这应该没有什么区别,因为函数应该在作为参数传入时制作自己的切片副本。
有人可以解释这种现象吗?

go slice pass-by-value
5个回答
249
投票

Go 中的一切都是按值传递的,切片也是。但是切片值是一个header,描述了支持数组的连续部分,并且切片值仅包含指向实际存储元素的数组的指针。切片值不包括其元素(与数组不同)。

因此,当您将切片传递给函数时,将从该标头创建一个副本,包括指针,该指针将指向相同的后备数组。修改切片的元素意味着修改支持数组的元素,因此共享相同支持数组的所有切片都将“观察”到更改。

要查看切片标头中的内容,请查看

reflect.SliceHeader
类型:

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
}

查看相关/可能重复的问题: 函数切片参数 vs 全局变量的性能?

阅读博文:Go Slices: usage and internals

请注意,当您将切片传递给函数时,如果函数修改切片的“现有”元素,调用者将看到/观察更改。如果函数向切片添加新元素,则需要更改切片标头(至少长度,但也可能涉及分配新的后备数组),调用者将看不到(在不返回新切片标头的情况下)。

不使用地图,因为地图是引擎盖下的指针,如果您将地图传递给函数并且函数向地图添加新条目,地图指针不会改变,因此调用者将看到更改后的地图(新的条目)更改后不返回地图。

关于切片和映射,请参阅Go 中的映射初始化为什么切片值有时会过时但永远不会映射值?


11
投票

你可以在下面找到一个例子。简而言之,切片也是按值传递的,但原始切片和复制的切片链接到相同的底层数组。如果其中一个切片发生变化,则底层数组发生变化,然后其他切片发生变化。

package main

import "fmt"

func main() {
    x := []int{1, 10, 100, 1000}
    double(x)
    fmt.Println(x) // ----> 3 will print [2, 20, 200, 2000] (original slice changed)
}

func double(y []int) {
    fmt.Println(y) // ----> 1 will print [1, 10, 100, 1000]
    for i := 0; i < len(y); i++ {
        y[i] *= 2
    }
    fmt.Println(y) // ----> 2 will print [2, 20, 200, 2000] (copy slice + under array changed)
}

4
投票

Slices 当它传递时,它是通过指向底层数组的指针传递的,所以 slice 是一个指向底层数组的小结构。复制了 small 结构,但它仍然指向相同的底层数组。包含切片元素的内存块通过“引用”传递。包含容量、元素数量和指向元素的指针的切片信息三元组按值传递。

处理传递给函数的切片的最佳方法(如果切片的元素被操作到函数中,并且我们不希望这反映在元素内存块中是使用

copy(s, *c)
将它们复制为:

package main

import "fmt"

type Team []Person
type Person struct {
    Name string
    Age  int
}

func main() {
    team := Team{
        Person{"Hasan", 34}, Person{"Karam", 32},
    }
    fmt.Printf("original before clonning: %v\n", team)
    team_cloned := team.Clone()
    fmt.Printf("original after clonning: %v\n", team)
    fmt.Printf("clones slice: %v\n", team_cloned)
}

func (c *Team) Clone() Team {
    var s = make(Team, len(*c))
    copy(s, *c)
    for index, _ := range s {
        s[index].Name = "change name"
    }
    return s
}

但是要小心,如果这个切片包含

sub slice
需要进一步复制,因为我们仍然有子切片元素共享指向相同的内存块元素,一个例子是:

type Inventories []Inventory
type Inventory struct { //instead of: map[string]map[string]Pairs
    Warehouse string
    Item      string
    Batches   Lots
}
type Lots []Lot
type Lot struct {
    Date  time.Time
    Key   string
    Value float64
}

func main() {
ins := Inventory{
        Warehouse: "DMM",
        Item:      "Gloves",
        Batches: Lots{
            Lot{mustTime(time.Parse(custom, "1/7/2020")), "Jan", 50},
            Lot{mustTime(time.Parse(custom, "2/1/2020")), "Feb", 70},
        },
    }

   inv2 := CloneFrom(c Inventories)
}

func (i *Inventories) CloneFrom(c Inventories) {
    inv := new(Inventories)
    for _, v := range c {
        batches := Lots{}
        for _, b := range v.Batches {
            batches = append(batches, Lot{
                Date:  b.Date,
                Key:   b.Key,
                Value: b.Value,
            })
        }

        *inv = append(*inv, Inventory{
            Warehouse: v.Warehouse,
            Item:      v.Item,
            Batches:   batches,
        })
    }
    (*i).ReplaceBy(inv)
}

func (i *Inventories) ReplaceBy(x *Inventories) {
    *i = *x
}

3
投票

Slice 可以通过值传递给函数,但是我们不应该使用 append 向函数中的 slice 添加值,而应该直接使用赋值。原因是 append 将创建新内存并将值复制到其中。这是例子。

去游乐场

     // Go program to illustrate how to
        // pass a slice to the function
        package main
        
        import "fmt"
        
        // Function in which slice
        // is passed by value
        func myfun(element []string) {
        
            // Here we only modify the slice
            // Using append function
            // Here, this function only modifies
            // the copy of the slice present in
            // the function not the original slice
            element = append(element, "blackhole")
            fmt.Println("Modified slice: ", element)
        }
        
        func main() {
        
            // Creating a slice
            slc := []string{"rocket", "galaxy", "stars", "milkyway"}
            fmt.Println("Initial slice: ", slc)
            //slice pass by value
            myfun(slc)
            fmt.Println("Final slice: ", slc)
        }
Output-
    Initial slice:  [rocket galaxy stars milkyway]
    Modified slice:  [rocket galaxy stars milkyway blackhole]
    Final slice:  [rocket galaxy stars milkyway]

去游乐场

    // Go program to illustrate how to
        // pass a slice to the function
        package main
        import "fmt"
        
        // Function in which slice
        // is passed by value
        func myfun(element []string) {
        
            // Here we only modify the slice
            // Using append function
            // Here, this function only modifies
            // the copy of the slice present in
            // the function not the original slice
            element[0] = "Spaceship"
            element[4] = "blackhole"
            element[5] = "cosmos"
            fmt.Println("Modified slice: ", element)
        }
        
        func main() {
        
            // Creating a slice
            slc := []string{"rocket", "galaxy", "stars", "milkyway", "", ""}
            fmt.Println("Initial slice: ", slc)
            //slice pass by value
            myfun(slc)
            fmt.Println("Final slice: ", slc)
        }
Output-
    Initial slice:  [rocket galaxy stars milkyway  ]
    Modified slice:  [Spaceship galaxy stars milkyway blackhole cosmos]
    Final slice:  [Spaceship galaxy stars milkyway blackhole cosmos]

1
投票

为了补充这篇文章,这里有一个您分享的 Golang PlayGround 的引用传递示例:

type point struct {
    x int
    y int
}

func main() {
    data := []point{{1, 2}, {3, 4}, {5, 6}, {7, 8}}
    makeRandomDatas(&data)
}

func makeRandomDatas(dataPoints *[]point) {
    for i := 0; i < 10; i++ {
        if len(*dataPoints) > 0 {
            fmt.Println(makeRandomData(dataPoints))
        } else {
            fmt.Println("no more elements")
        }
    }

}

func makeRandomData(cities *[]point) []point {
    solution := []point{(*cities)[0]}                 //create a new slice with the first item from the old slice
    *cities = append((*cities)[:0], (*cities)[1:]...) //remove the first item from the old slice
    return solution

}
© www.soinside.com 2019 - 2024. All rights reserved.