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.