Golang指针定义

huangapple go评论139阅读模式
英文:

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}

huangapple
  • 本文由 发表于 2017年6月5日 07:45:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/44359916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定