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.

GoConfig Management

Code

gosnippet
35 lines
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

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.