英文:
Golang pointer definition
问题
伙计们,我有一个名为Student的结构体,我试图创建一个*Student类型的Student项。但是我得到了"无效的内存地址或空指针解引用"的错误。
var newStudent *Student
newStudent.Name = "John"
我是这样创建的。当我尝试设置任何变量时,都会出现相同的错误。我做错了什么?
英文:
Guys I have Student struct and I am trying to create Student item as *Student. I get invalid memory address or nil pointer dereference error.
var newStudent *Student
newStudent.Name = "John"
I m creating like that. When I try to set any variable, I am getting same error. What did I wrong?
答案1
得分: 5
你需要为Student
结构体分配内存。例如,
package main
import "fmt"
type Student struct {
Name string
}
func main() {
var newStudent *Student
newStudent = new(Student)
newStudent.Name = "John"
fmt.Println(*newStudent)
newStudent = &Student{}
newStudent.Name = "Jane"
fmt.Println(*newStudent)
newStudent = &Student{Name: "Jill"}
fmt.Println(*newStudent)
}
输出结果:
{John}
{Jane}
{Jill}
英文:
You need to allocate memory for the Student
struct
. For example,
package main
import "fmt"
type Student struct {
Name string
}
func main() {
var newStudent *Student
newStudent = new(Student)
newStudent.Name = "John"
fmt.Println(*newStudent)
newStudent = &Student{}
newStudent.Name = "Jane"
fmt.Println(*newStudent)
newStudent = &Student{Name: "Jill"}
fmt.Println(*newStudent)
}
Output:
{John}
{Jane}
{Jill}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论