Golang中指针和结构体的使用问题求助
Golang中指针和结构体的使用问题求助 这两个结构体用于存储数据:
type Collection struct {
First *Element
Last *Element
}
type Element struct {
Value int
Next *Element
}
我以如下形式向它们传递数据:
collection := Collection{}
for i := 0; i < 5; i++ {
collection.AddToCollection(i)
}
func (c *Collection) AddToCollection(Value int) {
newElement := Element{}
newElement.Value = Value
if c.First == nil {
c.First = &newElement
} else {
c.Last.Next = &newElement
}
c.Last = &newElement
}
我不理解这是如何工作的。
更多关于Golang中指针和结构体的使用问题求助的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
在Golang中,你的代码存在一个关键问题:newElement是局部变量,但你在存储它的指针。当函数返回时,这个局部变量的内存可能被重用,导致指针失效。正确的做法应该是使用new()或取地址操作符来分配堆内存。
以下是修正后的代码:
type Collection struct {
First *Element
Last *Element
}
type Element struct {
Value int
Next *Element
}
func (c *Collection) AddToCollection(value int) {
newElement := &Element{Value: value}
if c.First == nil {
c.First = newElement
} else {
c.Last.Next = newElement
}
c.Last = newElement
}
// 使用示例
func main() {
collection := &Collection{}
for i := 0; i < 5; i++ {
collection.AddToCollection(i)
}
// 遍历验证
current := collection.First
for current != nil {
fmt.Println(current.Value)
current = current.Next
}
}
或者使用new()函数:
func (c *Collection) AddToCollection(value int) {
newElement := new(Element)
newElement.Value = value
if c.First == nil {
c.First = newElement
} else {
c.Last.Next = newElement
}
c.Last = newElement
}
关键区别:
&Element{Value: value}直接在堆上创建Element并返回指针new(Element)分配零值Element并返回指针- 这两种方式都确保Element在函数返回后仍然有效
你的原始代码中,newElement是栈上的局部变量,函数返回后其内存可能被覆盖,导致链表中的指针指向无效内存。

