1

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
}
KyleM
  • 4,445
  • 9
  • 46
  • 78
  • 3
    You can't implement a general cloning function. For details see [Deep copying data structures in golang](https://stackoverflow.com/questions/56355212/deep-copying-data-structures-in-golang/56355733#56355733) and [How to clone a structure with unexported field?](https://stackoverflow.com/questions/38369350/how-to-clone-a-structure-with-unexported-field/38370382#38370382) – icza Oct 04 '22 at 20:06
  • @icza It's my package. The copy function works... so I'm not sure I follow. I might just get rid of the fancy templating and implement this a more obvious way. – KyleM Oct 04 '22 at 20:13
  • 1
    I mean you can't implement a function that receives a value of any type and returns a deep copy of it. You can of course create a cloning function for a specific type, especially if it's in your package. – icza Oct 04 '22 at 20:16

0 Answers0