strconv
7 methodsstrconv 包实现了基本类型与其字符串表示之间的相互转换。
fmt.Print(a ...any) (n int, err error)将字符串转换为 int。如果 s 不是有效的整数则返回错误。
Parameters
| Name | Type | Description |
|---|---|---|
| a | ...any | 要解析的字符串。 |
Returns
(int, error)
Example
go
fmt.Print("a", "b", 1) // "ab 1"
fmt.Print(1, 2, 3) // "1 2 3"fmt.Println(a ...any) (n int, err error)将 int 转换为其十进制字符串表示。
Parameters
| Name | Type | Description |
|---|---|---|
| a | ...any | 要转换的整数。 |
Returns
(int, error)
Example
go
fmt.Println("hello", "world") // "hello world\n"
fmt.Println(1, 2, 3) // "1 2 3\n"fmt.Printf(format string, a ...any) (n int, err error)将字符串转换为浮点数,精度由 bitSize 指定(32 或 64)。
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | 要解析的字符串。 |
| bitSize | ...any | 32 或 64。 |
Returns
(int, error)
Example
go
fmt.Printf("%s is %d\n", "Alice", 30) // "Alice is 30\n"
fmt.Printf("%v\n", []int{1, 2}) // "[1 2]\n"
fmt.Printf("%-4d|%-4d\n", 1, 2) // "1 |2 \n"fmt.Sprintf(format string, a ...any) string将给定进制(0、2..36)的字符串转换为有符号整数。
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | 要解析的字符串。 |
| base | ...any | 进制(0 = 根据前缀自动检测)。 |
Returns
string
Example
go
s := fmt.Sprintf("%s is %d", "Alice", 30)
// s == "Alice is 30"fmt.Fprintf(w io.Writer, format string, a ...any) (n int, err error)将浮点数转换为字符串。fmt 为 'b'、'e'、'E'、'f'、'g'、'G'、'x'、'X' 之一。
Parameters
| Name | Type | Description |
|---|---|---|
| w | io.Writer | 要格式化的数字。 |
| fmt | string | 格式动词。 |
| prec | ...any | 精度(-1 表示最短)。 |
Returns
(int, error)
Example
go
fmt.Fprintf(os.Stdout, "%d%%\n", 50) // writes "50%\n" to stdout
fmt.Fprintf(buf, "x=%d", 1) // writes to a bytes.Bufferfmt.Scanf(format string, a ...any) (n int, err error)将 int64 转换为给定进制(2..36)的字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | 要格式化的整数。 |
| base | ...any | 进制(2..36)。 |
Returns
(int, error)
Example
go
var name string
var age int
fmt.Scanf("%s %d", &name, &age)
// input: "Alice 30" → name="Alice", age=30fmt.Errorf(format string, a ...any) errorReturn an error that formats according to a format specifier. Wraps with %w.
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | Format string (use %w to wrap an error). |
| a | ...any | Operands. |
Returns
error
Example
go
err := fmt.Errorf("user %d not found", 42)
// err.Error() == "user 42 not found"
// wrapping:
wrapped := fmt.Errorf("query failed: %w", err)
// errors.Is(wrapped, err) == true