亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

切片在復制并使用副本后發生變化

切片在復制并使用副本后發生變化

Go
千萬里不及你 2022-06-06 17:58:15
我編寫了這段代碼來制作切片副本,它工作正常,作為參數傳遞給函數的主切片不受影響:package mainimport "fmt"type Team []Persontype 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}但是在我的其他代碼中,即使我將原始切片傳遞clone給函數,原始切片也會發生變化:type Inventories []Inventorytype Inventory struct { //instead of: map[string]map[string]Pairs    Warehouse string    Item      string    Batches   Lots}type Lots []Lottype Lot struct {    Date  time.Time    Key   string    Value float64}func (c *Inventories) Clone() Inventories {    var s = make(Inventories, len(*c))    copy(s, *c)    return s}func (outs Inventories) BuildBatchesFrom(ins Inventories) (batchesBalance Inventories, outgoing Inventories) {    batchesOut := Inventories{}    for _, in := range batchesBalance {        for _, out := range outgoing {            if out.Warehouse == in.Warehouse && out.Item == in.Item {                batches := Lots{}            OUTER:                for {                    oldestBatch := in.Batches.First()                    batchQty := math.Min(in.Batches.First().Value, math.Abs(out.Batches.First().Value))                    batches = append(batches, Lot{out.Batches.First().Date, oldestBatch.Key, batchQty})                    out.Batches[0].Value = out.Batches.First().Value + batchQty                    in.Batches[0].Value = oldestBatch.Value - batchQty                    if in.Batches.First().Value == 0 {                        in.Batches.PopFirst()                    }在上面,ins運行函數后正在發生變化,盡管我沒有將它傳遞到那里,并且ins_clone()在函數之后發生變化,盡管我在函數代碼的第一行克隆了它,對于outs和outs_clone()
查看完整描述

1 回答

?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

我明白了,原因是我的切片包含一個sub slice所以copy對頂部有用但不適用于共享相同數據的子切片,我通過創建一個新切片重寫代碼來修復它,推送數據到它,然后用它來替換原來的數據,如下所示:


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

}


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號