SoFunction
Updated on 2025-03-02

Go language implements string conversion with other types (strconv package)

The type conversions related to strings are implemented through the strconv package.

Overview of strconv package

strconv is the abbreviation of two words. string convert = strconv

The strconv package is located in the Go standard library and provides a series of functions for converting between strings and basic data types. These functions mainly include the following types:

  • Functions that convert basic data types to strings, such as Itoa, FormatInt, FormatFloat, FormatBool, etc.
  • Functions that parse strings into basic data types, such as Atoi, ParseInt, ParseFloat, ParseBool, etc.
  • Functions that are attached to existing byte arrays, such as AppendInt, AppendFloat, AppendBool, etc.
  • Other helper functions, such as IsPrint, IsGraphic, Quote, Unquote, etc.

The process of converting a string to other basic types is called parse, and the process of converting other basic types to strings becomes formatted

1. Convert string and int type

1.1. The Atoi() function is used to convert integers of string type to int type
(s string) (i int, err error)

becausestringMay not convert toint,So there are two return values:The first return value is converted tointvalue,第二个返回value判断是否转换成功

//var age ="22 years old" conversion failedvar age ="22" // Conversion is successfulage1,err:=(age)
if err != nil {
    ("The conversion error occurred")
    return
}else {
    ("Type is: %T, value is: %d",age1,age1)
}

1.2. Itoa() function is used to convert int type data into corresponding string representations
(i int) string

i := 100
s := (i)
("Type is:%T value is:%#v\n", s2, s2) // Type is: string Value is: "999"

2. Parse series functions

Parse class functions are used to convert strings to values ​​of a given type: ParseBool(), ParseFloat(), ParseInt(), ParseUint()

2.1、ParseBool()(str string) (value bool, err error)

Returns the string representationboolvalue,它只接受value为1、0、t、f、T、F、true、false、True、False、TRUE、FALSEstring,Otherwise, an error will be returned

(("1"))    // true
(("t"))    // true
(("T"))    // true
(("true")) // true
(("True")) // true
(("TRUE")) // true
(("0"))     // false
(("f"))     // false
(("F"))     // false
(("false")) // false
(("False")) // false
(("FALSE")) // false

2.2. ParseInt() returns the integer value represented by a string, accepting positive and negative signs
(s string, base int, bitSize int) (i int64, err error)

  • s: The string to be converted
  • base: Specify the binary system (binary to hexadecimal). When base=0, it means to judge which binary system is used to parse according to the prefix of string: 0x is used to parse in hexadecimal, 0 is used to parse in octal, and others are used to parse in decimal.
  • bitSize: plays a restrictive role when string is converted to int, and the valid values ​​are 0, 8, 16, 32, 64. If the bitSize limit effect is exceeded, the error message will be output to the error
  • Returns the result after conversion and the error of the conversion failure
//Conversion is successfuls1 := "123"
ps1,err := (s1, 10, 8) // refers to converting s1 into a decimal number, 8 means that the maximum value of the conversion result does not exceed int8, that is, 127if err != nil{
	("err is %v\n", err)
	return
}else{
	("Type: %T, value: %d", ps1, ps1) //Type: int64, value: 123}

//Conversion faileds1 := "129" // Maximum value exceeds int8 127ps1,err := (s1, 10, 8) // refers to converting s1 into a decimal number, 8 means that the maximum value of the conversion result does not exceed int8, that is, 127if err != nil{
	("err is %v\n", err)
	return
}else{
	("Type: %T, value: %d", ps1, ps1) //err is : parsing "129": value out of range
}

2.3 ParseUint()ParseUint is similar to ParseInt but does not accept positive and negative signs, and is used for unsigned integers.
(s string, base int, bitSize int) (i int64, err error)

2.4、ParseFloat()(s string, bitSize int) (f float64, err error)

  • s: The string to be converted
  • bitSize: Specify the floating point type (32:float32, 64:float64)
  • If s is a legal format and is close to a floating point value, the rounded value of the floating point number is returned
  • If s is not a legal format, a "grammatical error" is returned
  • If the conversion result is outside the bitSize range, "out of range" is returned
	f := "1.2342332"
	f1, err := (f, 64)
	if err != nil {
		("err is %v\n", err)
		return
	} else {
		("Type: %T, value: %f", f1, f1)
	} //Type is: float64, value is: 1.234230

3. Format series functions

Format the given type to string type data

3.1. FormatBool() is used to convert the value of Boolean type to a string type
(b bool) string

  • If the value of b is true, the string "true" will be returned, otherwise "false" will be returned
((0 < 1)) // true
((0 > 1)) // false
((true)) // Convert true to string

3.2、FormatInt()(i int64, base int) string

  • i: The type of integer to be converted
  • base: 2-32-digit, the lowercase letters 'a' to 'z' will be used to represent numbers greater than 10.
s3 := (-2, 16) 
("Type: %T, value: %#v",s3,s3) // Type is: string, value is: "-2"

3.3. FormatUint() is an unsigned integer version of FormatInt
(i int64, base int) string

3.4. FormatFloat() represents a floating point number as a string and returns
(f float64, fmt byte, prec, bitSize int) string

  • f: The floating point number to be converted
  • fmt represents format:
    ‘b’ (-ddddp±ddd, binary index)
    ‘e’ (-±dd, decimal index)
    ‘E’ (-±dd, decimal index)
    ‘f’ (-, no index)
    ‘g’ (‘e’:big index, ‘f’: other situations)
    ‘G’ (‘E’:Big Index, ‘f’:Other Situation)
  • Prec control accuracy
    If the format is marked ‘e’, ‘E’ and ‘f’, then prec represents the number of digits after the decimal point
    If the format is marked ‘g’, ‘G’, then prec represents the total number of digits (integer part + decimal part)
f := 100.123456789

((f, 'g', 5, 64))
// 100.12
((f, 'G', 5, 64))
// 100.12
((f, 'f', 5, 64))
// 100.12346
((f, 'e', 5, 64))
// 1.00123e+02
((f, 'E', 5, 64))
// 1.00123E+02

4. Append series

The functions of the Append class work similarly to the functions of the Format class, except that the converted result is appended to a slice.

4.1、AppendBool()(num1 []byte, num2 bool) []byte

  • Append bool (i.e. true or false) to num1 according to the value of num2 and return the extended buffer
val := []byte("Is Bool: ")
val = (val, true)    
(string(val)) // Is Bool: true

4.2、AppendFloat()(dst []byte, f float64, fmt byte, prec int, bitSize int) []byte

  • Convert the floating point number f to a string value and append the conversion result to the tail of dst
  • Return to the appended []byte
val1 := []byte("Float32 value:")
val1 = (val1,4.5683568954,'E',-1,32)
(string(val1))
val2 := []byte("Float64 value:")
val2 = (val2,6.7415678653,'E',-1,64)
(string(val2))

4.3. AppendInt() converts the int integer i into a string form and appends it to the end of dst
(dst []byte, i int64, base int) []byte

  • i: The string to be converted
  • base: carry system
  • Return to the appended []byte
val1 := []byte("Integer value(Pricing10): ")
val1 = (val1, -35, 10)
(string(val1)) //Integer value (Binary 10): -35  
val2 := []byte("Integer value(Pricing16): ")
val2 = (val2, -44, 16)
(string(val2)) //Integer value (Binary 16): -2c

4.4. AppendUint() is an unsigned integer version of AppendInt

5. Others

5.1. isPrint() returns whether a character is printable. r must be: letters (generalized), numbers, punctuation, symbols, ASCII spaces

res:=('n')  // true printableres:=('\n')  // false Not printable

5.2. CanBackquote() returns whether the string s can be expressed as a single line without modification, with no spaces or tabs, with backtick strings that control characters outside of the control character.

	res:=(`lxx is Nb`) // true
	res:=(`lxx is
Nb`) // false: because I brought it back to the car	(res)

This is the end of this article about the implementation of string and other types of conversion (strconv package) in Go language. For more related contents of go string conversion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!