【问题标题】:Golang pointer definitionGolang 指针定义
【发布时间】:2017-06-05 13:41:15
【问题描述】:

伙计们,我有 Student 结构,我正在尝试将 Student 项目创建为 *Student。我得到 invalid memory address or nil pointer dereference 错误。

var newStudent *Student
newStudent.Name = "John"

我就是这样创作的。当我尝试设置任何变量时,我得到了同样的错误。我做错了什么?

【问题讨论】:

  • 似乎没有分配用于保存Student 的内存。试试var newStudent *Student := new(Student)
  • 它的工作。非常感谢。

标签: pointers go


【解决方案1】:

你需要为Studentstruct分配内存。例如,

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}

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2014-10-12
    • 2018-10-24
    • 2015-01-10
    • 1970-01-01
    • 2017-06-21
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多