伙计们,我有学生结构,我正在尝试将学生项目创建为*学生。我收到无效的内存地址或nil指针取消引用错误。

var newStudent *Student
newStudent.Name = "John"

我正在创造那样。当我尝试设置任何变量时,出现相同的错误。我怎么了

最佳答案

您需要为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}

关于pointers - Golang指针定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44359916/

10-12 22:23