{"record":{"id":"9e5d691274ab639c","repo":"unknwon/the-way-to-go_ZH_CN","slug":"g-is-out-of-the-int32-range","errorCode":null,"errorMessage":"%g is out of the int32 range","messagePattern":"%g is out of the int32 range","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"eBook/04.5.md","lineNumber":216,"sourceCode":"\tif 0 <= n && n <= math.MaxUint8 { // conversion is safe\n\t\treturn uint8(n), nil\n\t}\n\treturn 0, fmt.Errorf(\"%d is out of the uint8 range\", n)\n}\n```\n\n或者安全地从 `float64` 转换为 `int`：\n\n```go\nfunc IntFromFloat64(x float64) int {\n\tif math.MinInt32 <= x && x <= math.MaxInt32 { // x lies in the integer range\n\t\twhole, fraction := math.Modf(x)\n\t\tif fraction >= 0.5 {\n\t\t\twhole++\n\t\t}\n\t\treturn int(whole)\n\t}\n\tpanic(fmt.Sprintf(\"%g is out of the int32 range\", x))\n}\n```\n\n不过如果你实际存的数字超出你要转换到的类型的取值范围的话，则会引发 `panic`（[第 13.2 节](./13.2.md)）。\n\n**问题 4.1** `int` 和 `int64` 是相同的类型吗？\n\n### 4.5.2.2 复数\n\nGo 拥有以下复数类型：\n\n\tcomplex64 (32 位实数和虚数)\n\tcomplex128 (64 位实数和虚数)\n\n复数使用 `re+imI` 来表示，其中 `re` 代表实数部分，`im` 代表虚数部分，`I` 代表根号负 1。\n\n示例：\n","sourceCodeStart":198,"sourceCodeEnd":234,"githubUrl":"https://github.com/unknwon/the-way-to-go_ZH_CN/blob/7a54d34d3657084b6a59e5618bd069b912d571aa/eBook/04.5.md#L198-L234","documentation":"Guard panic inside IntFromFloat64 (section 4.5): it refuses to convert a float64 to int when x falls outside [math.MinInt32, math.MaxInt32], panicking with '%g is out of the int32 range'. A raw Go float-to-int conversion in that situation silently overflows/truncates, so the function aborts instead of returning garbage. NaN and ±Inf also fail both comparisons and therefore panic too.","triggerScenarios":"Calling IntFromFloat64 with 1e20, float64(math.MaxInt32)*2, math.Inf(1), or math.NaN() — the two-sided range test 'math.MinInt32 <= x && x <= math.MaxInt32' is false for all of them.","commonSituations":"Aggregations (sums, averages) that grow past int32; converting user-parsed floats from strconv.ParseFloat; a division by zero producing +Inf that later flows into the conversion; 32-bit-platform assumptions baked into the constant.","solutions":["Range-check (or clamp) the value before calling: if math.MinInt32 <= x && x <= math.MaxInt32","Reject NaN and ±Inf explicitly before the conversion — they silently fail the range test and panic","Convert to int64 or keep float64 when the wider type suffices for the data","Refactor IntFromFloat64 to return (int, error) or (int, bool) instead of panicking so callers can react"],"exampleFix":"// before\nfunc IntFromFloat64(x float64) int {\n    if math.MinInt32 <= x && x <= math.MaxInt32 { ... }\n    panic(fmt.Sprintf(\"%g is out of the int32 range\", x))\n}\n\n// after\nfunc IntFromFloat64(x float64) (int, error) {\n    if math.IsNaN(x) || math.IsInf(x, 0) || x < math.MinInt32 || x > math.MaxInt32 {\n        return 0, fmt.Errorf(\"%g is out of the int32 range\", x)\n    }\n    return int(x), nil\n}","handlingStrategy":"validation","validationCode":"func convertibleToInt32(x float64) bool {\n    if math.IsNaN(x) || math.IsInf(x, 0) {\n        return false\n    }\n    return math.MinInt32 <= x && x <= math.MaxInt32\n}\n\nif !convertibleToInt32(v) {\n    return 0, fmt.Errorf(\"value %g not representable as int32\", v)\n}\nreturn IntFromFloat64(v), nil","typeGuard":"// narrows float64 inputs to the safe-conversion subset\nfunc isSafeInt32Float(x float64) bool {\n    return !math.IsNaN(x) && !math.IsInf(x, 0) &&\n        x >= math.MinInt32 && x <= math.MaxInt32\n}","tryCatchPattern":"defer func() {\n    if r := recover(); r != nil {\n        return 0, fmt.Errorf(\"conversion failed: %v\", r)\n    }\n}()\nreturn IntFromFloat64(x), nil","preventionTips":["Check numeric bounds at parse time (strconv.ParseFloat plus range check) before any conversion","Use strconv.ParseInt directly when the input is semantically an integer","Remember NaN comparisons are always false — special-case NaN/Inf explicitly"],"tags":["go","math","type-conversion","overflow","panic","float64"],"backgroundTag":null,"analyzedSha":"7a54d34d3657084b6a59e5618bd069b912d571aa","analyzedAt":"2026-08-15T15:13:06.026Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}