I have a working Push/Pop/Length function for my Stack, and I want to implement a Clone() function but cannot figure out how. I believe I could do it if I moved the slice into the type definition, but I feel there's a more elegant way.
type stack[T any] struct {
Push func(T)
Pop func() T
Length func() int
Clone func() stack[T]
}
func Stack[T any]() stack[T] {
slice := make([]T, 0)
return stack[T]{
Push: func(i T) {
slice = append(slice, i)
},
Pop: func() T {
res := slice[len(slice)-1]
slice = slice[:len(slice)-1]
return res
},
Clone: func() stack[T] {
newSlice := make([]T, len(slice))
copy(newSlice, slice)
return stack[T]{} // ????
},
Length: func() int {
return len(slice)
},
}
}
Alternate without func in the struct. This is what I'm going for..
type stack struct {
slice []uint
}
func (stack *stack) Clone() *stack {
s := Stack()
original := stack.Get()
s.slice = make([]uint, len(original))
copy(s.slice, original)
return &s
}
func (stack *stack) Push(i uint) {
stack.slice = append(stack.slice, i)
}
func (stack *stack) Pop() uint {
res := stack.slice[len(stack.slice)-1]
stack.slice = stack.slice[:len(stack.slice)-1]
return res
}
func (stack *stack) Get() []uint {
return stack.slice
}
func (stack *stack) Length() int {
return len(stack.slice)
}
func Stack() stack {
s := stack{}
s.slice = make([]uint, 0)
return s
}