初學go時的問題 panic: runtime error: invalid memory address or nil pointer dereference


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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM