Golang指针定义

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?

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}