亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

內存錯誤,Go 中的 html/模板

內存錯誤,Go 中的 html/模板

Go
慕的地8271018 2021-09-27 10:55:41
嘗試執行此代碼時出現一些內存錯誤:package webimport (    "net/http"    "html/template")type Hello struct {    Level string}func Main(w http.ResponseWriter, r *http.Request) {    h := Hello{Level: "gsdfg"}    t, _ := template.ParseFiles("web.html")    t.Execute(w, h)}我在瀏覽器中得到的錯誤信息是這樣的:the runtime process gave a bad HTTP response: ''2015/03/26 11:34:56 http: panic serving 127.0.0.1:43269: runtime error: invalid memory address or nil pointer dereference我不明白我做錯了什么......
查看完整描述

2 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

template.ParseFiles返回錯誤


func ParseFiles(filenames ...string) (*Template, error)

如果發生錯誤,則解析停止并返回*Templatenil。


如果出現問題,您應該檢查錯誤。

這可以解釋為什么 ' t' 可能為零。


一般來說,最好的做法是永遠不要忽略錯誤。


這里:


var t *Template

if t, err := template.ParseFiles("web.html"); err != nil {

    // do something

    // return err

    // or

    // panic(err)

}


查看完整回答
反對 回復 2021-09-27
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

另一種解決方案是使用template.Must函數在出現錯誤時引起恐慌。在這種情況下,它的使用是合理的,因為程序需要它的資源。

t := template.Must(template.ParseFiles("web.html"))


查看完整回答
反對 回復 2021-09-27
  • 2 回答
  • 0 關注
  • 209 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號