我正在Go中实现队列。
type Node struct {
Value interface{}
Next *Node
}
type Queue struct {
Front *Node
Rear *Node
}
func (q *Queue) IsEmpty() bool {
if q.Front == nil {
return true
}
return false
}
func (q *Queue) Dequeue() (interface{}, error) {
if q.IsEmpty() {
return nil, errors.New(constants.EMPTY)
}
tmp := q.Front
result := tmp.Value
q.Front = q.Front.Next
if q.Front == nil {
q.Front = nil
q.Rear = nil
}
tmp = nil // free tmp
return result, nil
}
在出队功能中,我是否需要通过将tmp指针设置为nil来释放它,否则Go会帮我实现吗?请为我详细解释。
谢谢!
答案 0 :(得分:1)
Go具有垃圾回收功能,因此它将释放它不包含引用的内存空间。
Dequeue
函数结束时,您将失去对为您出队的变量分配的空间的引用,垃圾回收器将释放该空间。您不必将其淘汰。