首頁  >  文章  >  後端開發  >  修改切片副本中的值然後附加到原始切片

修改切片副本中的值然後附加到原始切片

PHPz
PHPz轉載
2024-02-09 16:36:07380瀏覽

修改切片副本中的值然後附加到原始切片

在PHP中,切片(Slice)是一種常用的資料結構,它允許我們從一個陣列或切片中選取一部分元素。然而,有時候我們需要對切片進行修改,並將修改後的值附加到原始切片中。這種操作在PHP中是可以實現的,透過修改切片副本中的值,然後使用array_splice函數將修改後的副本附加到原始切片中即可。在本文中,我們將詳細介紹如何使用此方法實現切片的修改和附加操作。

問題內容

編寫一個函數來複製切片並修改切片副本中項目的值,然後將副本附加到原始副本。看起來程式碼不僅修改了切片的副本,還修改了原始切片。

去遊樂場

import "fmt"

type item struct {
    name   string
    number int
}

func main() {
    names := []string{"a", "b"}
    numbers := []int{1, 2}

    items := []*item{}

    for _, name := range names {
        item := &item{name: name}
        items = append(items, item)
    }

    for n, i := range numbers {
        if n > 0 {
            fmt.println(n, "make a copy of the items")
            itemcopies := make([]*item, len(items))
            copy(itemcopies, items)

            fmt.println(n, "set the numbers on the copies")
            for _, item := range itemcopies {
                item.number = i
            }

            fmt.println(n, "append the copies to the original")
            items = append(items, itemcopies...)
        } else {

            fmt.println(n, "first pass set all the items to the first number")
            for _, item := range items {
                item.number = i
            }
        }
    }

    for n, i := range items {
        fmt.printf("%d %+v\n", n, *i)
    }
}

我實際看到的

0 {name:a number:2}
1 {name:b number:2}
2 {name:a number:2}
3 {name:b number:2}

我期望看到什麼

0 {name:a number:1}
1 {name:b number:1}
2 {name:a number:2}
3 {name:b number:2}

解決方法

@jimb 是對的,你複製指針,

我建議定義一個屬於struct item的copy函數來新建一個副本

package main

import "fmt"

type Item struct {
    name   string
    number int
}

func (it *Item) copy() *Item {
    return &Item{
        name:   it.name,
        number: it.number,
    }
}
func main() {
    names := []string{"a", "b"}
    numbers := []int{1, 2}

    items := []*Item{}

    for _, name := range names {
        item := &Item{name: name}
        items = append(items, item)
    }

    for n, i := range numbers {
        if n > 0 {
            fmt.Println(n, "make a copy of the items")
            itemCopies := make([]*Item, len(items))

            for j := 0; j < len(items); j++ {
                itemCopies[j] = items[j].copy()
            }
            fmt.Println(n, "set the numbers on the copies")
            for _, item := range itemCopies {
                item.number = i
            }

            fmt.Println(n, "append the copies to the original")
            items = append(items, itemCopies...)
        } else {

            fmt.Println(n, "first pass set all the items to the first number")
            for _, item := range items {
                item.number = i
            }
        }
    }

    for n, i := range items {
        fmt.Printf("%d %+v\n", n, *i)
    }
}

以上是修改切片副本中的值然後附加到原始切片的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除