首页 > 解决方案 > 我需要释放指针吗

问题描述

我正在 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
}

在 Dequeue 函数中,我是否需要通过将 tmp 指针设置为 nil 来释放它,或者 Go 会为我做这件事?请为我详细解释。

提前致谢!

标签: gogarbage-collection

解决方案


Go 有垃圾收集,所以它会释放它没有引用的内存空间。

Dequeue函数结束时,您将失去对为您出列的变量分配的空间的引用,垃圾收集器将释放它。你不必否定它。


推荐阅读