登录
首页 >  Golang >  Go问答

golang中结构体切片的理解方法

来源:stackoverflow

时间:2024-02-03 19:58:16 460浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《golang中结构体切片的理解方法》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我是 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

有人可以帮我理解为什么会这样吗?

如果你能在记忆层面上解释一下那就太好了。

例如: 我们在 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的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>