%w 是用于錯誤包裝(Error Wrapping)的格式化動詞。它是用于 fmt.Errorf 和 fmt.Sprintf 函數(shù)中的一個特殊格式化動詞,用于將一個錯誤(或其他可打印的值)包裝在一個新的錯誤中。
使用 %w 時,它會在格式化字符串中占據(jù)一個位置,并將其后的錯誤作為參數(shù)傳遞給 fmt.Errorf 或 fmt.Sprintf 函數(shù)。這將創(chuàng)建一個新的錯誤,包含了原始錯誤信息,并形成一個錯誤鏈。
下面是一個示例,展示了如何使用 %w 來進行錯誤包裝:
package mainimport ( "errors" "fmt")func doSomething() error { return errors.New("something went wrong")}func main() { err := doSomething() // Wrap the original error with additional context wrappedErr := fmt.Errorf("encountered an issue: %w", err) fmt.Println(wrappedErr) // Output: encountered an issue: something went wrong if err, ok := wrappedErr.(interface{ Unwrap() error }); ok { // wrappedErr是error類型,只支持Error()方法,所以沒辦法直接調(diào)用Unwrap()。但是wrappedErr.(interface{ Unwrap() error })取出內(nèi)部的數(shù)據(jù)就可以調(diào)用Unwrap()了 fmt.Println("internal error:", err.Unwrap()) } fmt.Println(errors.Is(wrappedErr, err)) // Output: true fmt.Println(errors.Is(err, fmt.Errorf("something went wrong"))) // Output: false}另外,還有一種interface{ Unwrap() []error },其實是多次用了%w的結果。
本文鏈接:http://www.www897cc.com/showinfo-26-96-0.html一篇聊聊Go錯誤封裝機制
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com