panic: runtime error: invalid memory address or nil pointer dereference
場景:在做練習時遇到了指針的問題,沒有給指針分配地址,就直接給指針賦值
Q:定義結構體 Address 和 VCard,后者包含一個人的名字、地址編號、出生日期和圖像,試着選擇正確的數據類型。構建一個自己的 vcard 並打印它的內容。
代碼
1 package main 2 3 import ( 4 "fmt" 5 ) 6 7 type Address struct { 8 localId int 9 street string 10 phone string 11 } 12 13 type VCard struct { 14 name string 15 address *Address 16 birth string 17 } 18 19 func main() { 20 var VCard1 VCard 21 VCard1.name = "Tim" 22 //要在給VCard1.address.localId賦值之前,給VCard1.address分配地址 23 VCard1.address = new(Address) 24 VCard1.address.localId = 12 25 VCard1.address.street = "hexing Road" 26 VCard1.address.phone = "13517086342" 27 VCard1.birth = "1993/09/14" 28 29 fmt.Printf(VCard1.name) 30 }