1

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?

2
  • 2
    It seems that the memory to hold a Student is not allocated. Try var newStudent *Student := new(Student) Commented Jun 4, 2017 at 23:49
  • it s work. Thanks a lot. Commented Jun 4, 2017 at 23:55

1 Answer 1

5

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}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.