最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

go - How to perform deepcopy on a field of a struct in its method - Stack Overflow

programmeradmin5浏览0评论

Consider the following util package containing an implementation of a stack

package util

type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(item T) {
    s.items = append(s.items, item)
}

func (s *Stack[T]) Pop() T {
    if len(s.items) == 0 {
        panic("Stack underflow")
    }
    item := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return item
}

Consider another type blockStack and the usage as follows

package main

import (
    "fmt"
    "project/util"
)

type typedOperand struct {
    typ      int
    filePath string
    row      int
}

type blockStack struct {
    stack util.Stack[typedOperand]
    typ   int
}

func main() {
    var stack = new(util.Stack[typedOperand])
    var blockStacks = new(util.Stack[blockStack])
    stack.Push(typedOperand{ 0, "filePath", 0 })
    blockStacks.Push(blockStack {*stack, 0})
    fmt.Printf("%+v\n", blockStacks)
    stack.Pop()
    stack.Push(typedOperand{ 1, "anotherFile", 1 })
    fmt.Printf("%+v\n", blockStacks)
}

This program output the following:

&{items:[{stack:{items:[{typ:0 filePath:filePath row:0}]} typ:0}]}
&{items:[{stack:{items:[{typ:1 filePath:anotherFile row:1}]} typ:0}]}

I want the the blockStacks to contain an independent copy of stack, how do I go about doing it?

I am using the stack variable at various places, I know the solution is to refactor Push method, but I don't want to rework the stack variable too much.

发布评论

评论列表(0)

  1. 暂无评论