我需要释放指针吗
Do I need to free pointer
我正在 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 会为我做这件事?请详细解释一下。
提前致谢!
Go 有垃圾收集功能,所以它会释放它没有引用的内存 space。
当 Dequeue
函数结束时,您将丢失对为您出队的变量分配的 space 的引用,垃圾收集器将释放它。您不必将其消除。
我正在 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 会为我做这件事?请详细解释一下。
提前致谢!
Go 有垃圾收集功能,所以它会释放它没有引用的内存 space。
当 Dequeue
函数结束时,您将丢失对为您出队的变量分配的 space 的引用,垃圾收集器将释放它。您不必将其消除。