Golang pointer definition

时间:2017-06-04 23:45:48

标签: pointers go

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 个答案:

答案 0 :(得分:5)

您需要为Student struct分配内存。例如,

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}