Strconv Parsing With Defaults And Errors
Parse config strings with strconv using Atoi, ParseFloat, ParseBool, and ParseUint, inspecting NumError fields and falling back to defaults.
Code
package main
import (
"errors"
"fmt"
"strconv"
)
func parsePort(raw string) int {
// 解析失败时回退 default 值:配置读取的常见收尾
port, err := strconv.Atoi(raw)
if err != nil {
return 8080
}
return port
}
func main() {
port, err := strconv.Atoi("8080")
fmt.Println("port:", port, "err:", err)
// NumError 拆出哪一步、哪个输入失败
_, err = strconv.Atoi("80-80")
var numErr *strconv.NumError
if errors.As(err, &numErr) {
fmt.Println("failed func:", numErr.Func, "input:", numErr.Num)
}
ratio, _ := strconv.ParseFloat("0.75", 64)
debug, _ := strconv.ParseBool("true")
workers, _ := strconv.ParseUint("3", 10, 8)
fmt.Println("ratio:", ratio, "debug:", debug, "workers:", workers)
fmt.Println("fallback:", parsePort("not-a-number"))
}What the code does
Strconv Parsing With Defaults And Errors is built around the functions parsePort and main.
Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Applying it
Entry signature: func parsePort(raw string) int
The demo output is labeled (port:, failed func:, ratio:), so each line traces straight back to the statement that printed it.
Running the file executes main, which drives parsePort in order.
Statements that matter
func parsePort(raw string) int {
// 解析失败时回退 default 值:配置读取的常见收尾
port, err := strconv.Atoi(raw)
if err != nil {
return 8080
}
return port
}
if errors.As(err, &numErr) {
fmt.Println("failed func:", numErr.Func, "input:", numErr.Num)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Strconv Parsing With Defaults And Errors print when run?
- Invoke the file as-is — the `port:`, `failed func:`, `ratio:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.