{"record":{"id":"f5273c1a653bb2fa","repo":"unknwon/the-way-to-go_ZH_CN","slug":"d-is-out-of-the-uint8-range","errorCode":null,"errorMessage":"%d is out of the uint8 range","messagePattern":"(.+?) is out of the uint8 range","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"eBook/04.5.md","lineNumber":201,"sourceCode":"16 bit int is: 34\n```\n\n**格式化说明符**\n\n在格式化字符串里，`%d` 用于格式化整数（`%x` 和 `%X` 用于格式化 16 进制表示的数字），`%g` 用于格式化浮点型（`%f` 输出浮点数，`%e` 输出科学计数表示法），`%0nd` 用于规定输出长度为 n 的整数，其中开头的数字 0 是必须的。\n\n`%n.mg` 用于表示数字 n 并精确到小数点后 m 位，除了使用 g 之外，还可以使用 e 或者 f，例如：使用格式化字符串 `%5.2e` 来输出 3.4 的结果为 `3.40e+00`。\n\n**数字值转换**\n\n当进行类似 `a32bitInt = int32(a32Float)` 的转换时，小数点后的数字将被丢弃。这种情况一般发生当从取值范围较大的类型转换为取值范围较小的类型时，或者你可以写一个专门用于处理类型转换的函数来确保没有发生精度的丢失。下面这个例子展示如何安全地从 `int` 型转换为 `int8`：\n\n```go\nfunc Uint8FromInt(n int) (uint8, error) {\n\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","sourceCodeStart":183,"sourceCodeEnd":219,"githubUrl":"https://github.com/unknwon/the-way-to-go_ZH_CN/blob/7a54d34d3657084b6a59e5618bd069b912d571aa/eBook/04.5.md#L183-L219","documentation":"Range-guard error from the safe-conversion helper in section 4.5: Uint8FromInt(n int) allows only 0..math.MaxUint8 and otherwise returns 0 plus fmt.Errorf(\"%d is out of the uint8 range\", n). The book introduces it because Go's raw int→uint8 conversion silently truncates (keeps the low 8 bits), so a checked helper is the way to make narrowing conversions safe and reportable.","triggerScenarios":"Calling Uint8FromInt with n < 0 or n > 255. Raw uint8(n) would wrap 256→0 and -1→255; the helper catches exactly those cases. Typical sources: sums exceeding 255 (color channels, byte counters, scaled percentages) or signed intermediates that dipped negative.","commonSituations":"Image/audio processing where per-sample math overflows a byte; config values parsed as int from flags or JSON then narrowed; cross-platform code where int is 64-bit and masks produce large values; porting C code that relied on implicit wraparound.","solutions":["Clamp before converting when saturation is the correct behavior: n = min(max(n, 0), math.MaxUint8)","Reject at the input boundary: validate parsed config values against [0,255] with a clear message before any conversion happens","Widen the destination field (int32/int64) so the range question disappears","Apply the same checked-helper pattern (the sibling IntFromFloat64 in this section) to every narrowing conversion in the path so overflow is caught once, precisely"],"exampleFix":"// before\nb := uint8(n) // n = 300 → 44; silent wraparound, no error\n\n// after\nb, err := Uint8FromInt(n)\nif err != nil {\n\treturn fmt.Errorf(\"channel value: %v\", err)\n}","handlingStrategy":"validation","validationCode":"func fitsUint8(n int) bool {\n\treturn n >= 0 && n <= math.MaxUint8\n}\n\nif !fitsUint8(n) {\n\treturn fmt.Errorf(\"rejecting %d before conversion\", n)\n}\nb := uint8(n)","typeGuard":null,"tryCatchPattern":"b, err := Uint8FromInt(n)\nif err != nil {\n\treturn fmt.Errorf(\"field out of range: %v\", err)\n}","preventionTips":["Range-check before every narrowing conversion; uint8(raw) silently wraps modulo 256","Clamp when saturation is acceptable, reject when it is not — decide per field, not globally","Validate parsed config/JSON numbers against the target field range at ingest","Table-test conversion helpers at boundary values 0, 255, 256, and -1"],"tags":["go","integer-overflow","conversion","range-check"],"backgroundTag":null,"analyzedSha":"7a54d34d3657084b6a59e5618bd069b912d571aa","analyzedAt":"2026-08-15T15:13:06.026Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}