Go does not perform implicit type conversion on data, but can only perform the conversion manually.
Simple conversion operation
It is easy to convert data types.
valueOfTypeB = typeB(valueOfTypeA)
For example:
// Floating point number A: = 5.0 // convert to int Type B: = int ()
Go allows mutual conversion between two types with the same underlying structure. For example:
// The underlying it type is int type it int // The underlying it type is it, the underlying is intvar A it = 5 // convert a (IT) to int, B is now int Type B: = int (5) // convert B (INT) to it, C is now it type C: = It (B)
Note:
- Not all data types can be converted. For example, converting the string type of the letter format "ABCD" to int will certainly fail.
- It is safe to convert low-Precision values to High-Precision values, and loss of precision when converting High-Precision values to low-Precision values. For example, convert int32 to int16 and float32 to int.
- This simple conversion method cannot convert int (float) and string. You can use
strconv
Functions provided by the package
Strconv
The strconv package provides the type conversion function between simple data types. You can convert a simple type to a string, or convert a string to another simple type.
This package provides many functions, which are roughly divided into several categories:
- String to int: atoi ()
- Int to string: ITOA ()
- Parsetp functions convert the string type to the TP type: parsebool (), parsefloat (), parseint (), and parseuint (). Because conversion from string to other types may fail, the second return value of these functions indicates whether the conversion is successful.
- Other types to the string type: formatbool (), formatfloat (), formatint (), formatuint ()
- Appendtp functions are used to append a string to a server Load balancer: appendbool (), appendfloat (), appendint (), appenduint ()
There are other functions that are basically unavailable. For details, refer to the official manual:go doc strconv
Or https://golang.org/pkg/strconv /.
If some types cannot be converted, an error is returned. The returned error is the custom error type in the strconv package. There are two types of errors:
var ErrRange = errors.New("value out of range")var ErrSyntax = errors.New("invalid syntax")
For example, if you use atoi ("A") to convert "a" to the int type, it is not successful. If Print outputs err information, the following information is displayed:
strconv.Atoi: parsing "a": invalid syntax
String and INT Conversion
The most common conversion is between a string and an int:
1.int to string: ITOA ()
// Itoa(): int -> stringprintln("a" + strconv.Itoa(32)) // a32
2. Convert string to int: atoi ()
func Atoi(s string) (int, error)
Since string may not be converted to int, this function has two return values: the first return value is the value converted to int, and the second return value determines whether the conversion is successful.
// Atoi (): String-> Inti, _: = strconv. atoi ("3") println (3 + I) // 6 // atoi () Conversion failed I, err: = strconv. atoi ("A") if Err! = Nil {println ("converted failed ")}
Parse functions
The parse function is used to convert a string to a value of the given type.: Parsebool (), parsefloat (), parseint (), parseuint ().
Conversion of strings to other types may fail, so these functions have two return values. The first return value stores the converted value, and the second return value determines whether the conversion is successful.
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)
Parsefloat () can only receive float64 floating point numbers.
Parseint () and parseuint () have three parameters:
func ParseInt(s string, base int, bitSize int) (i int64, err error)func ParseUint(s string, base int, bitSize int) (uint64, error)
bitSize
This parameter indicates the INT/uint of the bit to be converted. Valid values include 0, 8, 16, 32, and 64. When bitsize = 0, it indicates the conversion to int or uint type. For example, bitsize = 8 indicates the type of the converted value is int8 or uint8.
base
The parameter indicates the hexadecimal method used to parse a given string. The valid values are 0 and 2-36. When base = 0, it indicates to determine the base to be parsed Based on the string Prefix:0x
It is parsed in hexadecimal format at the beginning,0
It is parsed in octal format, and the other is parsed in decimal format.
Parses "-42" in decimal mode and saves it as int64 type:
i, _ := strconv.ParseInt("-42", 10, 64)
Parse "23" in a 5-digit format and save it as an int64 type:
i, _ := strconv.ParseInt("23", 5, 64)println(i) // 13
Because in the 5-digit system, 23 indicates that the number of carry characters is 2 and 3 is added, so the corresponding decimal number is5*2+3=13
.
Parse 23 in hexadecimal format and save it as int64 type:
i, _ := strconv.ParseInt("23", 16, 64)println(i) // 35
Because in hexadecimal notation, 23 indicates that it is carried twice, plus 3, so the corresponding decimal number is16*2+3=35
.
Parse 23 in hexadecimal notation and save as int64 type:
i, _ := strconv.ParseInt("23", 15, 64)println(i) // 33
Because in the 15th decimal system, 23 indicates that the carry is 2 times, plus 3, so the corresponding decimal number is15*2+3=33
.
Format functions
Format a given type to a string type.: Formatbool (), formatfloat (), formatint (), formatuint ().
s := strconv.FormatBool(true)s := strconv.FormatFloat(3.1415, 'E', -1, 64)s := strconv.FormatInt(-42, 16)s := strconv.FormatUint(42, 16)
Formatint () and formatuint () have two parameters:
func FormatInt(i int64, base int) stringfunc FormatUint(i uint64, base int) string
The second parameter base specifies the number of hexadecimal values to convert the first parameter. The valid value is2<=base<=36
. When the specified hexadecimal value is greater than 10, the value exceeding 10 is represented by a-Z. For example, in hexadecimal notation, the numbers 10-15 are represented by a-f, and in hexadecimal notation 17, the values 10-16 are represented by a-g, respectively.
For example:FormatInt(-42, 16)
Converts-42 to a hexadecimal number and the result is-2a.
There are many formatfloat () parameters:
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
The bitsize parameter indicates the number of BITs (32 or 64) to be converted.
Append Functions
Appendtp functions are used to append a string to a server Load balancer: appendbool (), appendfloat (), appendint (), and appenduint ().
Functions of the append class work in a similar way as those of the format class, except that the converted result is appended to an slice.
Package mainimport ("FMT" "strconv") func main () {// declare an slice B10: = [] Byte ("int (base 10 ):") // convert to a 10-digit string and append it to the slice B10 = strconv. appendint (B10,-42, 10) FMT. println (string (B10) B6: = [] Byte ("int (base 16):") B6 = strconv. appendint (F8,-42, 16) FMT. println (string (F8 ))}
Output result:
int (base 10):-42int (base 16):-2a
Go basic series: data type conversion (strconv package)