我一直在研究Golang并且已经实现了一些数据结构来学习语言的工作原理.我在编写AVL树的代码时遇到了以下问题:
从结构指针方法分配主指针似乎在函数范围之外没有任何影响.例如tree.rotateLeftToRoot(),不会导致tree.left成为新树.
问题:有没有办法在Golang中的结构指针方法中重新指定指针,或者这通常是不鼓励的?在示例中,这将是"tree = prevLeft"行.
代码段:
//Graphical representation of t.rotateLeftToRoot():
// t L
// L R -> LL t
//LL LR LR R
func (tree *AvlTree) rotateLeftToRoot() {
if tree == nil {
return
}
prevLeft := tree.left
if prevLeft != nil {
tree.left = prevLeft.right //tree.left passed root its right branch
prevLeft.right = tree //tree becomes tree.left's right branch
tree.updateHeight()
prevLeft.updateHeight()
tree = prevLeft //desired behaviour: tree.left becomes the new tree
//actual …Run Code Online (Sandbox Code Playgroud) 为什么这两个destroy函数不将指针更改为 nil 以及如何创建这样的函数?
package main
import (
"fmt"
)
type position struct {
x int
y int
}
func (p *position) destroy() {
p = nil
}
func destroy(p *position) {
p = nil
}
func main() {
p1 := &position{1,1}
p2 := &position{2,2}
p1.destroy()
destroy(p2)
if p1 == nil {
fmt.Println("p1 == nil")
} else {
fmt.Println(p1)
}
if p2 == nil {
fmt.Println("p2 == nil")
} else {
fmt.Println(p2)
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
&{1 1}
&{2 2} …Run Code Online (Sandbox Code Playgroud) 我的问题很简单,但我相信它隐藏了 Go 变量初始化的重要特征。
如果我们有两个变量
i := 5
d := &i
Run Code Online (Sandbox Code Playgroud)
我们想打印它们
fmt.Printf("The address of i value is %d\n", &i)
fmt.Printf("The value of d is %d\n", d)
fmt.Printf("The address of d is %d", &d)
Run Code Online (Sandbox Code Playgroud)
输出将类似于
The address of i value is 824633835664
The value of d is 824633835664
The address of d is 824633778224
Run Code Online (Sandbox Code Playgroud)
所以它看起来像&i返回其值的地址5。明白了。我们不明白的是那&d还什么?变量的地址i?
那么是不是这样实现的,值有自己的地址,变量(是值内存地址的别名)在内存中也有自己的地址呢?否则&d将返回我们的地址5