使用Golang中的类型断言检测超出范围错误的值 [英] Detect value out of range errors using type assertion in Golang
问题描述
给出以下代码:
iv,err:= strconv.ParseInt(18446744073709551448,10,64)
fmt.Println(iv)
fmt.Printf(%#v \ n,err)
fmt.Printf(%v \ n,err)
//输出:
9223372036854775807
& strconv.NumError {Func:ParseInt,Num:18446744073709551448,Err:(* errors.errorString)(0x1040a040)}
strconv.ParseInt:解析18446744073709551448:值超出范围
如何检测函数由于超出了int64的范围而失败? strconv.ParseInt 函数返回一个错误类型,但在这种情况下它实际上是由%#v $>指示的 strconv.NumError 类型C $ C>。 错误处理和Go 文章提到您可以使用类型断言来检查特定类型的错误,但它没有给出任何例子。我应该用什么样的表达来完成这段代码:
if表达式{
uv,err:= strconv.ParseUint( 18446744073709551448,10,64)
}
我们有,
$ b
var ErrRange = errors.New(value out of range)
ErrRange 表示值超出了目标类型的范围。
一>记录转换失败。type NumError struct {
Func string //失败函数( ParseBuff,ParseInt,ParseUint,ParseFloat)
数字字符串//输入
Err错误//转换失败的原因(ErrRange,ErrSyntax)
}
func(e * NumError)Error()string
例如,
b
$ b $ func main(){$ b $如果错误!= nil {
,如果numError,ok:= err。(* strconv.NumError); OK {
if numError.Err == strconv.ErrRange {
fmt.Println(Detected,numError.Num,as,strconv.ErrRange)
return
}
}
fmt.Println(err)
return
}
fmt.Println(iv)
}
$ c $输出:
检测到18446744073709551448作为一个值输出范围
Given the following code:
iv, err := strconv.ParseInt("18446744073709551448", 10, 64)
fmt.Println(iv)
fmt.Printf("%#v\n", err)
fmt.Printf("%v\n", err)
//Output:
9223372036854775807
&strconv.NumError{Func:"ParseInt", Num:"18446744073709551448", Err:(*errors.errorString)(0x1040a040)}
strconv.ParseInt: parsing "18446744073709551448": value out of range
How can I detect that the function failed due to being out of range of an int64? The strconv.ParseInt function returns an error type, but in this case it is actually a strconv.NumError type as indicated by %#v
. The Error Handling and Go article mentions you can use type assertion to check for specific types of errors, but it doesn't give any examples. What expression should I use to complete this code:
if expression {
uv, err := strconv.ParseUint("18446744073709551448", 10, 64)
}
解决方案 We have,
var ErrRange = errors.New("value out of range")
ErrRange indicates that a value is out of range for the target type.
type NumError struct {
Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat)
Num string // the input
Err error // the reason the conversion failed (ErrRange, ErrSyntax)
}
A NumError records a failed conversion.
func (e *NumError) Error() string
For example,
package main
import (
"fmt"
"strconv"
)
func main() {
iv, err := strconv.ParseInt("18446744073709551448", 10, 64)
if err != nil {
if numError, ok := err.(*strconv.NumError); ok {
if numError.Err == strconv.ErrRange {
fmt.Println("Detected", numError.Num, "as a", strconv.ErrRange)
return
}
}
fmt.Println(err)
return
}
fmt.Println(iv)
}
Output:
Detected 18446744073709551448 as a value out of range
这篇关于使用Golang中的类型断言检测超出范围错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!