2017-06-04 90 views
1

夥計們我有學生結構,我試圖創建Student項目作爲*學生。我得到無效內存地址或無指針解除引用錯誤。Golang指針定義

var newStudent *Student 
newStudent.Name = "John" 

我創建這樣的。當我嘗試設置任何變量時,我得到相同的錯誤。我錯了什麼?

+2

看來,內存來保存一個'Student'不分配。嘗試'var newStudent * Student:= new(Student)' –

+0

它工作。非常感謝。 –

回答

5

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