简体   繁体   English

在 Go 中实现堆栈以存储结构的正确方法是什么?

[英]What is the correct way to implement a stack in Go so that it will store structs?

I'm trying to make a stack that will store a series of Huffman Tree structs.我正在尝试制作一个堆栈来存储一系列霍夫曼树结构。 Currently I'm using an implementation that I found on github.目前我正在使用我在 github 上找到的实现。

package util

type item struct {
    value interface{}
    next  *item
}

//Stack the implementation of stack
//this stack is not thread safe!
type Stack struct {
    top  *item
    size int
}
// Basic stack methods...

The problem is that when I store my Huffman tree structs in the stack I can't use any of the fields of the Huffman tree such as left/right child.问题是,当我将霍夫曼树结构存储在堆栈中时,我不能使用霍夫曼树的任何字段,例如左/右孩子。

package huffmantree

type HuffmanTree struct {
    freq   int
    value  byte
    isLeaf bool
    left   *HuffmanTree
    right  *HuffmanTree
    code   []bool
    depth  int
}

How am I supposed to implement a stack in Go which will correctly store structs and allow access to their fields?我应该如何在 Go 中实现一个堆栈来正确存储结构并允许访问它们的字段?

Edit: I tried replacing the interface {} part with huffmantree.HuffmanTree (huffmantree struct) and got this error message:编辑:我尝试用huffmantree.HuffmanTree (huffmantree struct) 替换interface {}部分并收到此错误消息:

can't load package: import cycle not allowed
package github.com/inondle/huffman/util
    imports github.com/inondle/huffman/huffmantree
    imports github.com/inondle/huffman/util
import cycle not allowed

My guess would be that the huffmantree class imports the util package and the stack has to import the huffmantree package so there is some sort of conflict?我的猜测是 huffmantree 类导入了 util 包,而堆栈必须导入 huffmantree 包,所以存在某种冲突? Anyone know what went wrong?有谁知道出了什么问题?

The right way in go to implement a stack is simply to use a slice. go 实现堆栈的正确方法是使用切片。

stack := []*HuffmanTree{}

You can push to the stack using append , and pop by writing:您可以使用append推送到堆栈,并通过编写弹出:

v, stack := stack[len(stack)-1], stack[:len(stack)-1]

You could encapsulate it into its own type if you prefer, but a slice is easier to understand.如果您愿意,您可以将其封装成自己的类型,但切片更容易理解。

type Stack []*HuffmanTree{}

func NewStack() *Stack {
    var s []*HuffmanTree
    return (*Stack)(&s)
}

func (s *Stack) Pop() *HuffmanTree {
   if len(*s) == 0 {
      return nil
    }
    v = (*s)[len(*s)-1]
    *s = (*s)[:len(*s)-1]
    return v
}

func (s *Stack) Push(h *HuffmanTree) {
    *s = append(*s, h)
}

As icza observes, if the stacks live longer than the HuffmanTree objects, you may wish to zero the just-popped entry in your stack to allow the garbage collector to collect unreferenced objects.正如 icza 所观察到的,如果堆栈的存活时间比 HuffmanTree 对象长,您可能希望将堆栈中刚刚弹出的条目置零以允许垃圾收集器收集未引用的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM