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
2
i, _ := strconv.Atoi("-42")
fmt.Printf("%T, %d\n", i, i) // int, -42

These assume decimal and the Go int type.

ParseBool, ParseFloat, ParseInt, and ParseUint convert strings to values:

1
2
3
4
5
6
7
8
9
10
11
b, _ := strconv.ParseBool("true")
fmt.Printf("%T, %t\n", b, b) // bool, true

f, _ := strconv.ParseFloat("3.1415", 64)
fmt.Printf("%T, %f\n", f, f) // float64, 3.141500

i64, _ := strconv.ParseInt("-42", 10, 64)
fmt.Printf("%T, %d\n", i64, i64) // int64, -42

u, _ := strconv.ParseUint("42", 10, 64)
fmt.Printf("%T, %d\n", u, u) // uint64, 42

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
2
3
4
s := "2147483647" // biggest int32
i64, err := strconv.ParseInt(s, 10, 32)
// ...
i := int32(i64) // Error: cannot use int32(i64) (type int32) as type int in assignment

FormatBool, FormatFloat, FormatInt, and FormatUint convert values to strings:

1
2
3
4
5
6
7
8
9
10
11
s = strconv.FormatBool(true)
fmt.Printf("%T, %s\n", s, s) // string, true

s = strconv.FormatFloat(3.1415, 'E', -1, 64)
fmt.Printf("%T, %s\n", s, s) // string, 3.1415E+00

s = strconv.FormatInt(-42, 16)
fmt.Printf("%T, %s\n", s, s) // string, -2a

s = strconv.FormatUint(42, 16)
fmt.Printf("%T, %s\n", s, s) // string, 2a

AppendBool, AppendFloat, AppendInt, and AppendUint are similar but append the formatted value to a destination slice.

1
2
3
4
5
6
7
8
9
10
11
b := []byte("boolean:")
b = strconv.AppendFloat(b, true)
fmt.Println(string(b)) // boolean:true

b32 := []byte("float32:")
b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
fmt.Println(string(b32)) // float32:3.1415927E+00

b64 := []byte("float64:")
b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
fmt.Println(string(b64)) // float64:3.1415926535E+00

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
2
fmt.Println(strconv.Quote("Hello, 世界"))	// "Hello, 世界"
fmt.Println(strconv.QuoteToASCII("Hello, 世界")) // "Hello, \u4e16\u754c"

QuoteRune

QuoteRune and QuoteRuneToASCII are similar but accept runes and return quoted Go rune literals.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
r := strconv.QuoteRune('☺')
fmt.Printf("%T, %s\n", r, r) // string, '☺'

r = strconv.QuoteRuneToASCII('☺')
fmt.Printf("%T, %s\n", r, r) // string, '\u263a'

s = strconv.QuoteRuneToGraphic('☺')
fmt.Printf("%T, %s\n", s, s) // string, '☺'

s = strconv.QuoteRuneToGraphic('\u263a')
fmt.Printf("%T, %s\n", s, s) // string, '☺'

s = strconv.QuoteRuneToGraphic('\u000a')
fmt.Printf("%T, %s\n", s, s) // string, '\n'

s = strconv.QuoteRuneToGraphic(' ') // tab character
fmt.Printf("%T, %s\n", s, s) // string, '\t'

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
2
3
4
5
6
7
8
9
10
s, err := strconv.Unquote("You can't unquote a string without quotes")
fmt.Printf("%q, %v\n", s, err) // "", invalid syntax
s, err = strconv.Unquote("\"The string must be either double-quoted\"")
fmt.Printf("%q, %v\n", s, err) // "The string must be either double-quoted", <nil>
s, err = strconv.Unquote("`or backquoted.`")
fmt.Printf("%q, %v\n", s, err) // "or backquoted.", <nil>
s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotes
fmt.Printf("%q, %v\n", s, err) // "☺", <nil>
s, err = strconv.Unquote("'\u2639\u2639'")
fmt.Printf("%q, %v\n", s, err) // "", invalid syntax

UnquoteChar decodes the first character or byte in the escaped string or character literal represented by the string s. It returns four values:

    1. value, the decoded Unicode code point or byte value;
    1. multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
    1. tail, the remainder of the string after the character; and
    1. 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
2
3
4
5
v, mb, t, _ := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')

fmt.Println("value:", string(v)) // value: "
fmt.Println("multibyte:", mb) // multibyte: false
fmt.Println("tail:", t) // tail: Fran & Freddie's Diner\"

References

[1] strconv - The Go Programming Language - https://golang.org/pkg/strconv