strconv
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package strconv implements conversions to and from string representationsof basic data types.
Numeric Conversions¶
The most common numeric conversions areAtoi (string to int) andItoa (int to string).
i, err := strconv.Atoi("-42")s := strconv.Itoa(-42)These assume decimal and the Go int type.
ParseBool,ParseFloat,ParseInt, andParseUint convert strings to values:
b, err := strconv.ParseBool("true")f, err := strconv.ParseFloat("3.1415", 64)i, err := strconv.ParseInt("-42", 10, 64)u, err := strconv.ParseUint("42", 10, 64)The parse functions return the widest type (float64, int64, and uint64),but if the size argument specifies a narrower width the result can beconverted to that narrower type without data loss:
s := "2147483647" // biggest int32i64, err := strconv.ParseInt(s, 10, 32)...i := int32(i64)
FormatBool,FormatFloat,FormatInt, andFormatUint convert values to strings:
s := strconv.FormatBool(true)s := strconv.FormatFloat(3.1415, 'E', -1, 64)s := strconv.FormatInt(-42, 16)s := strconv.FormatUint(42, 16)
AppendBool,AppendFloat,AppendInt, andAppendUint are similar butappend the formatted value to a destination slice.
String Conversions¶
Quote andQuoteToASCII convert strings to quoted Go string literals.The latter guarantees that the result is an ASCII string, by escapingany non-ASCII Unicode with \u:
q := strconv.Quote("Hello, 世界")q := strconv.QuoteToASCII("Hello, 世界")QuoteRune andQuoteRuneToASCII are similar but accept runes andreturn quoted Go rune literals.
Unquote andUnquoteChar unquote Go string and rune literals.
Index¶
- Constants
- Variables
- func AppendBool(dst []byte, b bool) []byte
- func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
- func AppendInt(dst []byte, i int64, base int) []byte
- func AppendQuote(dst []byte, s string) []byte
- func AppendQuoteRune(dst []byte, r rune) []byte
- func AppendQuoteRuneToASCII(dst []byte, r rune) []byte
- func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte
- func AppendQuoteToASCII(dst []byte, s string) []byte
- func AppendQuoteToGraphic(dst []byte, s string) []byte
- func AppendUint(dst []byte, i uint64, base int) []byte
- func Atoi(s string) (int, error)
- func CanBackquote(s string) bool
- func FormatBool(b bool) string
- func FormatComplex(c complex128, fmt byte, prec, bitSize int) string
- func FormatFloat(f float64, fmt byte, prec, bitSize int) string
- func FormatInt(i int64, base int) string
- func FormatUint(i uint64, base int) string
- func IsGraphic(r rune) bool
- func IsPrint(r rune) bool
- func Itoa(i int) string
- func ParseBool(str string) (bool, error)
- func ParseComplex(s string, bitSize int) (complex128, error)
- func ParseFloat(s string, bitSize int) (float64, error)
- func ParseInt(s string, base int, bitSize int) (i int64, err error)
- func ParseUint(s string, base int, bitSize int) (uint64, error)
- func Quote(s string) string
- func QuoteRune(r rune) string
- func QuoteRuneToASCII(r rune) string
- func QuoteRuneToGraphic(r rune) string
- func QuoteToASCII(s string) string
- func QuoteToGraphic(s string) string
- func QuotedPrefix(s string) (string, error)
- func Unquote(s string) (string, error)
- func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
- type NumError
Examples¶
- AppendBool
- AppendFloat
- AppendInt
- AppendQuote
- AppendQuoteRune
- AppendQuoteRuneToASCII
- AppendQuoteToASCII
- AppendUint
- Atoi
- CanBackquote
- FormatBool
- FormatFloat
- FormatInt
- FormatUint
- IsGraphic
- IsPrint
- Itoa
- NumError
- ParseBool
- ParseFloat
- ParseInt
- ParseUint
- Quote
- QuoteRune
- QuoteRuneToASCII
- QuoteRuneToGraphic
- QuoteToASCII
- QuoteToGraphic
- QuotedPrefix
- Unquote
- UnquoteChar
Constants¶
const IntSize = intSizeIntSize is the size in bits of an int or uint value.
Variables¶
var ErrRange =errors.New("value out of range")ErrRange indicates that a value is out of range for the target type.
var ErrSyntax =errors.New("invalid syntax")ErrSyntax indicates that a value does not have the right syntax for the target type.
Functions¶
funcAppendBool¶
AppendBool appends "true" or "false", according to the value of b,to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b := []byte("bool:")b = strconv.AppendBool(b, true)fmt.Println(string(b))}Output:bool:true
funcAppendFloat¶
AppendFloat appends the string form of the floating-point number f,as generated byFormatFloat, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b32 := []byte("float32:")b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)fmt.Println(string(b32))b64 := []byte("float64:")b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)fmt.Println(string(b64))}Output:float32:3.1415927E+00float64:3.1415926535E+00
funcAppendInt¶
AppendInt appends the string form of the integer i,as generated byFormatInt, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b10 := []byte("int (base 10):")b10 = strconv.AppendInt(b10, -42, 10)fmt.Println(string(b10))b16 := []byte("int (base 16):")b16 = strconv.AppendInt(b16, -42, 16)fmt.Println(string(b16))}Output:int (base 10):-42int (base 16):-2a
funcAppendQuote¶
AppendQuote appends a double-quoted Go string literal representing s,as generated byQuote, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b := []byte("quote:")b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)fmt.Println(string(b))}Output:quote:"\"Fran & Freddie's Diner\""
funcAppendQuoteRune¶
AppendQuoteRune appends a single-quoted Go character literal representing the rune,as generated byQuoteRune, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b := []byte("rune:")b = strconv.AppendQuoteRune(b, '☺')fmt.Println(string(b))}Output:rune:'☺'
funcAppendQuoteRuneToASCII¶
AppendQuoteRuneToASCII appends a single-quoted Go character literal representing the rune,as generated byQuoteRuneToASCII, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b := []byte("rune (ascii):")b = strconv.AppendQuoteRuneToASCII(b, '☺')fmt.Println(string(b))}Output:rune (ascii):'\u263a'
funcAppendQuoteRuneToGraphic¶added ingo1.6
AppendQuoteRuneToGraphic appends a single-quoted Go character literal representing the rune,as generated byQuoteRuneToGraphic, to dst and returns the extended buffer.
funcAppendQuoteToASCII¶
AppendQuoteToASCII appends a double-quoted Go string literal representing s,as generated byQuoteToASCII, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b := []byte("quote (ascii):")b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)fmt.Println(string(b))}Output:quote (ascii):"\"Fran & Freddie's Diner\""
funcAppendQuoteToGraphic¶added ingo1.6
AppendQuoteToGraphic appends a double-quoted Go string literal representing s,as generated byQuoteToGraphic, to dst and returns the extended buffer.
funcAppendUint¶
AppendUint appends the string form of the unsigned integer i,as generated byFormatUint, to dst and returns the extended buffer.
Example¶
package mainimport ("fmt""strconv")func main() {b10 := []byte("uint (base 10):")b10 = strconv.AppendUint(b10, 42, 10)fmt.Println(string(b10))b16 := []byte("uint (base 16):")b16 = strconv.AppendUint(b16, 42, 16)fmt.Println(string(b16))}Output:uint (base 10):42uint (base 16):2a
funcAtoi¶
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
Example¶
package mainimport ("fmt""strconv")func main() {v := "10"if s, err := strconv.Atoi(v); err == nil {fmt.Printf("%T, %v", s, s)}}Output:int, 10
funcCanBackquote¶
CanBackquote reports whether the string s can be representedunchanged as a single-line backquoted string without controlcharacters other than tab.
Example¶
package mainimport ("fmt""strconv")func main() {fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))fmt.Println(strconv.CanBackquote("`can't backquote this`"))}Output:truefalse
funcFormatBool¶
FormatBool returns "true" or "false" according to the value of b.
Example¶
package mainimport ("fmt""strconv")func main() {v := trues := strconv.FormatBool(v)fmt.Printf("%T, %v\n", s, s)}Output:string, true
funcFormatComplex¶added ingo1.15
func FormatComplex(ccomplex128, fmtbyte, prec, bitSizeint)string
FormatComplex converts the complex number c to a string of theform (a+bi) where a and b are the real and imaginary parts,formatted according to the format fmt and precision prec.
The format fmt and precision prec have the same meaning as inFormatFloat.It rounds the result assuming that the original was obtained from a complexvalue of bitSize bits, which must be 64 for complex64 and 128 for complex128.
funcFormatFloat¶
FormatFloat converts the floating-point number f to a string,according to the format fmt and precision prec. It rounds theresult assuming that the original was obtained from a floating-pointvalue of bitSize bits (32 for float32, 64 for float64).
The format fmt is one of
- 'b' (-ddddp±ddd, a binary exponent),
- 'e' (-d.dddde±dd, a decimal exponent),
- 'E' (-d.ddddE±dd, a decimal exponent),
- 'f' (-ddd.dddd, no exponent),
- 'g' ('e' for large exponents, 'f' otherwise),
- 'G' ('E' for large exponents, 'f' otherwise),
- 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or
- 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).
The precision prec controls the number of digits (excluding the exponent)printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats.For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point.For 'g' and 'G' it is the maximum number of significant digits (trailingzeros are removed).The special precision -1 uses the smallest number of digitsnecessary such that ParseFloat will return f exactly.The exponent is written as a decimal integer;for all formats other than 'b', it will be at least two digits.
Example¶
package mainimport ("fmt""strconv")func main() {v := 3.1415926535s32 := strconv.FormatFloat(v, 'E', -1, 32)fmt.Printf("%T, %v\n", s32, s32)s64 := strconv.FormatFloat(v, 'E', -1, 64)fmt.Printf("%T, %v\n", s64, s64)// fmt.Println uses these arguments to print floatsfmt64 := strconv.FormatFloat(v, 'g', -1, 64)fmt.Printf("%T, %v\n", fmt64, fmt64)}Output:string, 3.1415927E+00string, 3.1415926535E+00string, 3.1415926535
funcFormatInt¶
FormatInt returns the string representation of i in the given base,for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'for digit values >= 10.
Example¶
package mainimport ("fmt""strconv")func main() {v := int64(-42)s10 := strconv.FormatInt(v, 10)fmt.Printf("%T, %v\n", s10, s10)s16 := strconv.FormatInt(v, 16)fmt.Printf("%T, %v\n", s16, s16)}Output:string, -42string, -2a
funcFormatUint¶
FormatUint returns the string representation of i in the given base,for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'for digit values >= 10.
Example¶
package mainimport ("fmt""strconv")func main() {v := uint64(42)s10 := strconv.FormatUint(v, 10)fmt.Printf("%T, %v\n", s10, s10)s16 := strconv.FormatUint(v, 16)fmt.Printf("%T, %v\n", s16, s16)}Output:string, 42string, 2a
funcIsGraphic¶added ingo1.6
IsGraphic reports whether the rune is defined as a Graphic by Unicode. Suchcharacters include letters, marks, numbers, punctuation, symbols, andspaces, from categories L, M, N, P, S, and Zs.
Example¶
package mainimport ("fmt""strconv")func main() {shamrock := strconv.IsGraphic('☘')fmt.Println(shamrock)a := strconv.IsGraphic('a')fmt.Println(a)bel := strconv.IsGraphic('\007')fmt.Println(bel)}Output:truetruefalse
funcIsPrint¶
IsPrint reports whether the rune is defined as printable by Go, withthe same definition asunicode.IsPrint: letters, numbers, punctuation,symbols and ASCII space.
Example¶
package mainimport ("fmt""strconv")func main() {c := strconv.IsPrint('\u263a')fmt.Println(c)bel := strconv.IsPrint('\007')fmt.Println(bel)}Output:truefalse
funcItoa¶
Itoa is equivalent toFormatInt(int64(i), 10).
Example¶
package mainimport ("fmt""strconv")func main() {i := 10s := strconv.Itoa(i)fmt.Printf("%T, %v\n", s, s)}Output:string, 10
funcParseBool¶
ParseBool returns the boolean value represented by the string.It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.Any other value returns an error.
Example¶
package mainimport ("fmt""strconv")func main() {v := "true"if s, err := strconv.ParseBool(v); err == nil {fmt.Printf("%T, %v\n", s, s)}}Output:bool, true
funcParseComplex¶added ingo1.15
func ParseComplex(sstring, bitSizeint) (complex128,error)
ParseComplex converts the string s to a complex numberwith the precision specified by bitSize: 64 for complex64, or 128 for complex128.When bitSize=64, the result still has type complex128, but it will beconvertible to complex64 without changing its value.
The number represented by s must be of the form N, Ni, or N±Ni, where N standsfor a floating-point number as recognized byParseFloat, and i is the imaginarycomponent. If the second N is unsigned, a + sign is required between the two componentsas indicated by the ±. If the second N is NaN, only a + sign is accepted.The form may be parenthesized and cannot contain any spaces.The resulting complex number consists of the two components converted by ParseFloat.
The errors that ParseComplex returns have concrete type*NumErrorand include err.Num = s.
If s is not syntactically well-formed, ParseComplex returns err.Err = ErrSyntax.
If s is syntactically well-formed but either component is more than 1/2 ULPaway from the largest floating point number of the given component's size,ParseComplex returns err.Err = ErrRange and c = ±Inf for the respective component.
funcParseFloat¶
ParseFloat converts the string s to a floating-point numberwith the precision specified by bitSize: 32 for float32, or 64 for float64.When bitSize=32, the result still has type float64, but it will beconvertible to float32 without changing its value.
ParseFloat accepts decimal and hexadecimal floating-point numbersas defined by the Go syntax forfloating-point literals.If s is well-formed and near a valid floating-point number,ParseFloat returns the nearest floating-point number roundedusing IEEE754 unbiased rounding.(Parsing a hexadecimal floating-point value only rounds whenthere are more bits in the hexadecimal representation thanwill fit in the mantissa.)
The errors that ParseFloat returns have concrete type *NumErrorand include err.Num = s.
If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.
If s is syntactically well-formed but is more than 1/2 ULPaway from the largest floating point number of the given size,ParseFloat returns f = ±Inf, err.Err = ErrRange.
ParseFloat recognizes the string "NaN", and the (possibly signed) strings "Inf" and "Infinity"as their respective special floating point values. It ignores case when matching.
Example¶
package mainimport ("fmt""strconv")func main() {v := "3.1415926535"if s, err := strconv.ParseFloat(v, 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat(v, 64); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat("NaN", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}// ParseFloat is case insensitiveif s, err := strconv.ParseFloat("nan", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat("inf", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat("+Inf", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat("-Inf", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat("-0", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseFloat("+0", 32); err == nil {fmt.Printf("%T, %v\n", s, s)}}Output:float64, 3.1415927410125732float64, 3.1415926535float64, NaNfloat64, NaNfloat64, +Inffloat64, +Inffloat64, -Inffloat64, -0float64, 0
funcParseInt¶
ParseInt interprets a string s in the given base (0, 2 to 36) andbit size (0 to 64) and returns the corresponding value i.
The string may begin with a leading sign: "+" or "-".
If the base argument is 0, the true base is implied by the string'sprefix following the sign (if present): 2 for "0b", 8 for "0" or "0o",16 for "0x", and 10 otherwise. Also, for argument base 0 only,underscore characters are permitted as defined by the Go syntax forinteger literals.
The bitSize argument specifies the integer typethat the result must fit into. Bit sizes 0, 8, 16, 32, and 64correspond to int, int8, int16, int32, and int64.If bitSize is below 0 or above 64, an error is returned.
The errors that ParseInt returns have concrete type*NumErrorand include err.Num = s. If s is empty or contains invaliddigits, err.Err =ErrSyntax and the returned value is 0;if the value corresponding to s cannot be represented by asigned integer of the given size, err.Err =ErrRange and thereturned value is the maximum magnitude integer of theappropriate bitSize and sign.
Example¶
package mainimport ("fmt""strconv")func main() {v32 := "-354634382"if s, err := strconv.ParseInt(v32, 10, 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseInt(v32, 16, 32); err == nil {fmt.Printf("%T, %v\n", s, s)}v64 := "-3546343826724305832"if s, err := strconv.ParseInt(v64, 10, 64); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseInt(v64, 16, 64); err == nil {fmt.Printf("%T, %v\n", s, s)}}Output:int64, -354634382int64, -3546343826724305832
funcParseUint¶
ParseUint is likeParseInt but for unsigned numbers.
A sign prefix is not permitted.
Example¶
package mainimport ("fmt""strconv")func main() {v := "42"if s, err := strconv.ParseUint(v, 10, 32); err == nil {fmt.Printf("%T, %v\n", s, s)}if s, err := strconv.ParseUint(v, 10, 64); err == nil {fmt.Printf("%T, %v\n", s, s)}}Output:uint64, 42uint64, 42
funcQuote¶
Quote returns a double-quoted Go string literal representing s. Thereturned string uses Go escape sequences (\t, \n, \xFF, \u0100) forcontrol characters and non-printable characters as defined byIsPrint.
Example¶
package mainimport ("fmt""strconv")func main() {// This string literal contains a tab character.s := strconv.Quote(`"Fran & Freddie's Diner☺"`)fmt.Println(s)}Output:"\"Fran & Freddie's Diner\t☺\""
funcQuoteRune¶
QuoteRune returns a single-quoted Go character literal representing therune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100)for control characters and non-printable characters as defined byIsPrint.If r is not a valid Unicode code point, it is interpreted as the Unicodereplacement character U+FFFD.
Example¶
package mainimport ("fmt""strconv")func main() {s := strconv.QuoteRune('☺')fmt.Println(s)}Output:'☺'
funcQuoteRuneToASCII¶
QuoteRuneToASCII returns a single-quoted Go character literal representingthe rune. The returned string uses Go escape sequences (\t, \n, \xFF,\u0100) for non-ASCII characters and non-printable characters as definedbyIsPrint.If r is not a valid Unicode code point, it is interpreted as the Unicodereplacement character U+FFFD.
Example¶
package mainimport ("fmt""strconv")func main() {s := strconv.QuoteRuneToASCII('☺')fmt.Println(s)}Output:'\u263a'
funcQuoteRuneToGraphic¶added ingo1.6
QuoteRuneToGraphic returns a single-quoted Go character literal representingthe rune. If the rune is not a Unicode graphic character,as defined byIsGraphic, the returned string will use a Go escape sequence(\t, \n, \xFF, \u0100).If r is not a valid Unicode code point, it is interpreted as the Unicodereplacement character U+FFFD.
Example¶
package mainimport ("fmt""strconv")func main() {s := strconv.QuoteRuneToGraphic('☺')fmt.Println(s)s = strconv.QuoteRuneToGraphic('\u263a')fmt.Println(s)s = strconv.QuoteRuneToGraphic('\u000a')fmt.Println(s)s = strconv.QuoteRuneToGraphic('') // tab characterfmt.Println(s)}Output:'☺''☺''\n''\t'
funcQuoteToASCII¶
QuoteToASCII returns a double-quoted Go string literal representing s.The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) fornon-ASCII characters and non-printable characters as defined byIsPrint.
Example¶
package mainimport ("fmt""strconv")func main() {// This string literal contains a tab character.s := strconv.QuoteToASCII(`"Fran & Freddie's Diner☺"`)fmt.Println(s)}Output:"\"Fran & Freddie's Diner\t\u263a\""
funcQuoteToGraphic¶added ingo1.6
QuoteToGraphic returns a double-quoted Go string literal representing s.The returned string leaves Unicode graphic characters, as defined byIsGraphic, unchanged and uses Go escape sequences (\t, \n, \xFF, \u0100)for non-graphic characters.
Example¶
package mainimport ("fmt""strconv")func main() {s := strconv.QuoteToGraphic("☺")fmt.Println(s)// This string literal contains a tab character.s = strconv.QuoteToGraphic("This is a \u263a\u000a")fmt.Println(s)s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)fmt.Println(s)}Output:"☺""This is a ☺\t\n""\" This is a ☺ \\n \""
funcQuotedPrefix¶added ingo1.17
QuotedPrefix returns the quoted string (as understood byUnquote) at the prefix of s.If s does not start with a valid quoted string, QuotedPrefix returns an error.
Example¶
package mainimport ("fmt""strconv")func main() {s, err := strconv.QuotedPrefix("not a quoted string")fmt.Printf("%q, %v\n", s, err)s, err = strconv.QuotedPrefix("\"double-quoted string\" with trailing text")fmt.Printf("%q, %v\n", s, err)s, err = strconv.QuotedPrefix("`or backquoted` with more trailing text")fmt.Printf("%q, %v\n", s, err)s, err = strconv.QuotedPrefix("'\u263a' is also okay")fmt.Printf("%q, %v\n", s, err)}Output:"", invalid syntax"\"double-quoted string\"", <nil>"`or backquoted`", <nil>"'☺'", <nil>
funcUnquote¶
Unquote interprets s as a single-quoted, double-quoted,or backquoted Go string literal, returning the string valuethat s quotes. (If s is single-quoted, it would be a Gocharacter literal; Unquote returns the correspondingone-character string. For an empty character literalUnquote returns the empty string.)
Example¶
package mainimport ("fmt""strconv")func main() {s, err := strconv.Unquote("You can't unquote a string without quotes")fmt.Printf("%q, %v\n", s, err)s, err = strconv.Unquote("\"The string must be either double-quoted\"")fmt.Printf("%q, %v\n", s, err)s, err = strconv.Unquote("`or backquoted.`")fmt.Printf("%q, %v\n", s, err)s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotesfmt.Printf("%q, %v\n", s, err)s, err = strconv.Unquote("'\u2639\u2639'")fmt.Printf("%q, %v\n", s, err)}Output:"", invalid syntax"The string must be either double-quoted", <nil>"or backquoted.", <nil>"☺", <nil>"", invalid syntax
funcUnquoteChar¶
UnquoteChar decodes the first character or byte in the escaped stringor 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 parsedand 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.
Example¶
package mainimport ("fmt""log""strconv")func main() {v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')if err != nil {log.Fatal(err)}fmt.Println("value:", string(v))fmt.Println("multibyte:", mb)fmt.Println("tail:", t)}Output:value: "multibyte: falsetail: Fran & Freddie's Diner\"
Types¶
typeNumError¶
type NumError struct {Funcstring// the failing function (ParseBool, ParseInt, ParseUint, ParseFloat, ParseComplex)Numstring// the inputErrerror// the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.)}A NumError records a failed conversion.
Example¶
package mainimport ("fmt""strconv")func main() {str := "Not a number"if _, err := strconv.ParseFloat(str, 64); err != nil {e := err.(*strconv.NumError)fmt.Println("Func:", e.Func)fmt.Println("Num:", e.Num)fmt.Println("Err:", e.Err)fmt.Println(err)}}Output:Func: ParseFloatNum: Not a numberErr: invalid syntaxstrconv.ParseFloat: parsing "Not a number": invalid syntax