
我是 golang 新手,正在尝试理解指针。
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
queue:=[]TreeNode{TreeNode{}}
node:=TreeNode{Val: 1}
pre:=queue[len(queue)-1]
pre.Left = &node但是我发现queue[0].Left仍然是nil
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
queue:=[]*TreeNode{&TreeNode{}}
node:=&TreeNode{Val: 1}
pre := queue[len(queue)-1]
pre.Left = node这次queue[0].Left不为nil
有人可以帮我理解为什么会这样吗?
立即学习“go语言免费学习笔记(深入)”;
如果你能在记忆层面上解释一下那就太好了。
例如: 我们在 0x1001 处有一个 TreeNode 切片 那么地址中存储了什么 以及切片如何链接到 A TreeNode,例如,地址 0x3001以下是第一段代码中发生的情况:
queue:=[]TreeNode{TreeNode{}}
node:=TreeNode{Val: 1}
// Copy last element of slice to local variable pre
pre:=queue[len(queue)-1]
// Assign field in local variable pre. The slice element is
// not modified.
pre.Left = &node这是第二个片段:
queue:=[]*TreeNode{&TreeNode{}}
node:=&TreeNode{Val: 1}
// Copy last element of queue to local variable pre.
// pre and the last element of queue have the same pointer
// value (it was just copied) and point at the same node.
pre := queue[len(queue)-1]
// Set the left field in the node that pre points to. queue[0]
// also points at this node.
// This code is syntactic sugar for (*pre).Left = node.
pre.Left = node要修复第一个示例,请修改切片元素而不是局部变量 pre。一种方法是使用指向切片元素的指针。
queue:=[]TreeNode{TreeNode{}}
node:=TreeNode{Val: 1}
// Variable pre is pointer to last element in slice.
pre:= &queue[len(queue)-1]
// Set the left field in the node that pre points to. This
// is the same value as queue[0].
pre.Left = &node以上就是如何理解golang中的结构体切片的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号