GO語言"errors"包中"As"函數的用法及代碼示例。
用法:
func As(err error, target any) bool
As 找到 err 鏈中與 target 匹配的第一個錯誤,如果找到,則將 target 設置為該錯誤值並返回 true。否則,它返回 false。
該鏈由 err 本身和通過重複調用 Unwrap 獲得的錯誤序列組成。
如果錯誤的具體值可分配給目標指向的值,或者錯誤具有方法 As(interface{}) bool 使得 As(target) 返回 true,則錯誤匹配目標。在後一種情況下,As 方法負責設置目標。
錯誤類型可能提供 As 方法,因此可以將其視為不同的錯誤類型。
如果 target 不是指向實現錯誤的類型或任何接口類型的非零指針,則會出現Panics。
例子:
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
if _, err := os.Open("non-existing"); err != nil {
var pathError *fs.PathError
if errors.As(err, &pathError) {
fmt.Println("Failed at path:", pathError.Path)
} else {
fmt.Println(err)
}
}
}
輸出:
Failed at path: non-existing
相關用法
- GO Asinh用法及代碼示例
- GO Asin用法及代碼示例
- GO AppendRune用法及代碼示例
- GO Atan2用法及代碼示例
- GO AppendQuoteRune用法及代碼示例
- GO Atan用法及代碼示例
- GO AppendInt用法及代碼示例
- GO Acos用法及代碼示例
- GO Acosh用法及代碼示例
- GO AppendBool用法及代碼示例
- GO Atoi用法及代碼示例
- GO AppendQuoteToASCII用法及代碼示例
- GO AppendFloat用法及代碼示例
- GO Add32用法及代碼示例
- GO Add64用法及代碼示例
- GO AppendQuoteRuneToASCII用法及代碼示例
- GO After用法及代碼示例
- GO AppendQuote用法及代碼示例
- GO AppendUint用法及代碼示例
- GO Atanh用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 As。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。