英文:
Invalid memory address or nil pointer dereference when appending to slice of structs
问题
以下是翻译的内容:
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 0)
p = append(p, &Person{"Brian"})
fmt.Println(p[0].name)
p = append(p, &Person{"Le Tu"})
fmt.Println(p[1].name)
}
上面的代码可以正常工作。
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 1) // 将0改为1
p = append(p, &Person{"Brian"})
fmt.Println(p[0].name)
p = append(p, &Person{"Le Tu"})
fmt.Println(p[1].name)
}
上面的代码会引发错误。
我对append
的理解是它隐藏了扩展/添加的机制。显然,我将append
视为切片的一种“推入”方式的心理模型是错误的。有人能解释一下为什么上面的第二个示例会引发错误吗?为什么我不能只是使用append
来添加我的结构体?
英文:
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 0)
p = append(p, &Person{"Brian"})
fmt.Println(p[0].name)
p = append(p, &Person{"Le Tu"})
fmt.Println(p[1].name)
}
The above works fine.
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 1) //Changed to 1 instead of 0
p = append(p, &Person{"Brian"})
fmt.Println(p[0].name)
p = append(p, &Person{"Le Tu"})
fmt.Println(p[1].name)
}
The above panics.
My understanding of append
was that it hid the mechanics of extending/adding. Clearly, my mental model of using append
as a sort of "push" for slices is incorrect. Can anyone explain to me why the second sample above panics? Why can't I just append
my struct?
答案1
得分: 7
例如,
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 1) //将0改为1
fmt.Println(len(p), p)
p = append(p, &Person{"Brian"})
fmt.Println(len(p), p)
fmt.Println(p[1].name)
fmt.Println(p[0])
fmt.Println(p[0].name)
}
输出结果:
1 [<nil>]
2 [<nil> 0x10500190]
Brian
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
在追加之前,p
的长度为1,追加之后长度为2。因此,p[0]
具有未初始化的指针值nil
,p[0].name
是无效的。
可变参数函数
append
将零个或多个值x
追加到类型为S
的切片s
中,并返回结果切片,类型也为S
。未初始化指针的值为
nil
。以下规则适用于选择器:
- 如果
x
是指针类型且具有值nil
,且x.f
表示结构字段,则对x.f
的赋值或求值会导致运行时恐慌。
英文:
For example,
package main
import (
"fmt"
)
type Person struct {
name string
}
func main() {
p := make([]*Person, 1) //Changed to 1 instead of 0
fmt.Println(len(p), p)
p = append(p, &Person{"Brian"})
fmt.Println(len(p), p)
fmt.Println(p[1].name)
fmt.Println(p[0])
fmt.Println(p[0].name)
}
Output:
1 [<nil>]
2 [<nil> 0x10500190]
Brian
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
p
has length 1 before the append, length 2 after. Therefore, p[0]
has the uninitialized pointer value nil
and p[0].name
is invalid.
> The Go Programming Language Specification
>
> Appending to and copying slices
>
> The variadic function append appends zero or more values x to s of
> type S, which must be a slice type, and returns the resulting slice,
> also of type S.
>
> Pointer types
>
> The value of an uninitialized pointer is nil.
>
> Selectors
>
> The following rules apply to selectors:
>
> 4) If x is of pointer type and has the value nil and x.f denotes a struct field, assigning to or evaluating x.f causes a run-time panic.
答案2
得分: 2
使用make
构建切片时,第一个整数参数是创建的切片的实际长度:
p := make([]*Person, 1)
// 等价于
p := []*Person{nil} // <- 长度为1的切片,单元格包含*Person类型的默认零值
如果你想创建长度为0但具有预定义容量的切片,需要使用make
的三个参数版本:
p := make([]*Person, 0, 100) // <- 长度为0的切片,但前100个append操作不会重新分配切片
一个简单的示例,演示如何使用这两种情况:
// 100个单元格的切片:
p1 := make([]*Person, 100)
for i := 0; i < 100; i++ {
name := fmt.Sprintf("Foo %d", i+1)
// 你可以访问并赋值给p1[i],因为p1有100个单元格:
p1[i] = &Person{name}
}
fmt.Printf("p1[0].Name: %s\n", p1[0].Name)
fmt.Printf("p1[99].Name: %s\n", p1[99].Name)
// 0个单元格,100个容量的切片:
p2 := make([]*Person, 0, 100)
for i := 0; i < 100; i++ {
name := fmt.Sprintf("Foo %d", i+1)
// 你无法访问p2[i],因为该单元格尚不存在:
p2 = append(p2, &Person{name})
}
fmt.Printf("p2[0].Name: %s\n", p2[0].Name)
fmt.Printf("p2[99].Name: %s\n", p2[99].Name)
英文:
When using make
to build a slice, the first integer argument is the actual length of the created slice :
p := make([]*Person, 1)
// is equivalent to
p := []*Person{nil} //<- slice of length 1, cells contain the default
// zero value for the *Person type
If you want to create a slice of length 0, but with a predefined capacity, you need to use the 3 arguments version of make
:
p := make([]*Person, 0, 100) //<- slice of length 0, but the first 100 append
// won't reallocate the slice
A simple example on how to use both cases :
//100-cell slice :
p1 := make([]*Person, 100)
for i := 0; i < 100; i++ {
name := fmt.Sprintf("Foo %d", i+1)
//you can access and assign to p1[i] because p1 has 100 cells :
p1[i] = &Person{name}
}
fmt.Printf("p1[0].Name : %s\n", p1[0].Name)
fmt.Printf("p1[99].Name : %s\n", p1[99].Name)
//0-cell, 100-capacity slice :
p2 := make([]*Person, 0, 100)
for i := 0; i < 100; i++ {
name := fmt.Sprintf("Foo %d", i+1)
//you cannot access p2[i], the cell doesn't exist yet :
p2 = append(p2, &Person{name})
}
fmt.Printf("p2[0].Name : %s\n", p2[0].Name)
fmt.Printf("p2[99].Name : %s\n", p2[99].Name)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论