strconv convert between string and basic data types in Golang (Go)
strconv
Package strconv implements conversions to and from string representations of basic data types.
The most common numeric conversions are Atoi
(string to int) and Itoa
(int to string).
1 | i, _ := strconv.Atoi("-42") |
These assume decimal and the Go int type.
ParseBool
, ParseFloat
, ParseInt
, and ParseUint
convert strings to values:
1 | b, _ := strconv.ParseBool("true") |
The parse functions return the widest type (float64
, int64
, and uint64
), but if the size argument specifies a narrower width the result can be converted to that narrower type without data loss:
1 | s := "2147483647" // biggest int32 |
FormatBool
, FormatFloat
, FormatInt
, and FormatUint
convert values to strings:
1 | s = strconv.FormatBool(true) |
AppendBool
, AppendFloat
, AppendInt
, and AppendUint
are similar but append the formatted value to a destination slice.
1 | b := []byte("boolean:") |
Quote
and QuoteToASCII
Quote
and QuoteToASCII
convert strings to quoted Go string literals. The latter guarantees that the result is an ASCII string, by escaping any non-ASCII Unicode with \u
:
1 | fmt.Println(strconv.Quote("Hello, 世界")) // "Hello, 世界" |
QuoteRune
QuoteRune
and QuoteRuneToASCII
are similar but accept runes and return quoted Go rune literals.
1 | r := strconv.QuoteRune('☺') |
Unquote
and UnquoteChar
Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)
1 | s, err := strconv.Unquote("You can't unquote a string without quotes") |
UnquoteChar decodes the first character or byte in the escaped string or character literal represented by the string s. It returns four values:
-
- value, the decoded Unicode code point or byte value;
-
- multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
-
- tail, the remainder of the string after the character; and
-
- an error that will be nil if the character is syntactically valid.
The second argument, quote, specifies the type of literal being parsed and therefore which escaped quote character is permitted. If set to a single quote, it permits the sequence ’ and disallows unescaped '. If set to a double quote, it permits " and disallows unescaped ". If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.
1 | v, mb, t, _ := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"') |
References
[1] strconv - The Go Programming Language - https://golang.org/pkg/strconv