Home  >  Article  >  Backend Development  >  Go language data type conversion tutorial

Go language data type conversion tutorial

尚
forward
2019-12-30 17:49:172371browse

Go language data type conversion tutorial

#Go does not perform implicit type conversion of data and can only perform conversion operations manually. Let's take a look at the method of data type conversion in go language .

Simple conversion operation

The way to convert data types is very simple.

valueOfTypeB = typeB(valueOfTypeA)

For example:

// 浮点数
a := 5.0

// 转换为int类型
b := int(a)

Go allows conversion between two types with the same underlying structure. For example:

// IT类型的底层是int类型
type IT int

// a的类型为IT,底层是int
var a IT = 5

// 将a(IT)转换为int,b现在是int类型
b := int(5)

// 将b(int)转换为IT,c现在是IT类型
c := IT(b)

But note:

1. Not all data types can be converted, for example, the string type "abcd" in alphabetical format can be converted to int. It will definitely fail

2. It is safe to convert low-precision to high-precision. However, precision will be lost when high-precision values ​​are converted to low-precision. For example, convert int32 Convert to int16 and float32 to int

3. This simple conversion method cannot convert int (float) and string to and from each other. To convert across large types, you can use The function provided by the strconv package

strconv

The strconv package provides type conversion functions between strings and simple data types. Simple types can be converted to characters Strings can also be converted to other simple types.

This package provides many functions, which are roughly divided into several categories:

1. Convert string to int: Atoi()

2. Convert int to string: Itoa ()

3. ParseTP class function converts string to TP type: ParseBool(), ParseFloat(), ParseInt(), ParseUint(). Because converting string to other types may fail, these functions have a second return value indicating whether to convert Successful conversion

4. FormatTP class function converts other types to string: FormatBool(), FormatFloat(), FormatInt(), FormatUint()

5. The AppendTP class function is used to convert TP into a string and then append it to a slice: AppendBool(), AppendFloat(), AppendInt(), AppendUint()

and some other functions that are basically unused, see the official manual: go doc strconv or https://golang.org/pkg/strconv/.

When some types cannot be converted, an error will be reported. The error returned is the self-defined error type in the strconv package. There are two kinds Error:

var ErrRange = errors.New("value out of 

range")
var ErrSyntax = errors.New("invalid syntax")

For example, using Atoi("a") to convert "a" to int type is naturally unsuccessful. if Print outputs err information and will display:

strconv.Atoi: parsing "a": invalid 

syntax

Conversion between string and int

The most common one is the conversion between string and int:

1. Convert int to string: Itoa()

// Itoa(): int -> string
println("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 value: The first return value is converted to int value, and the second return value determines whether the conversion is successful.

// Atoi(): string -> int
i,_ := strconv.Atoi("3")
println(3 + i)   // 6
// Atoi()转换失败
i,err := strconv.Atoi("a")
if err != nil {
    println("converted failed")
}

Parse class function

Parse class function is used to convert strings into values ​​of a given type: ParseBool(), ParseFloat(), ParseInt(), ParseUint().

Since string conversion to other types may fail, these functions have two return values, the first return value is saved The converted value, 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 type floating point numbers.

ParseInt() and ParseUint() have 3 parameters:

func ParseInt(s string, base int, bitSize int) 

(i int64, err error)
func ParseUint(s string, base int, bitSize int) (uint64, error)

The bitSize parameter indicates what bit of int/uint to convert to, and the valid values ​​are 0, 8, 16, 32, and 64. When bitSize=0 When, it means converting to int or uint type. For example, bitSize=8 indicates that the type of the converted value is int8 or uint8.

The base parameter indicates the base method to use to parse the given string. Valid values ​​are 0 and 2-36. When base=0 , indicating that the prefix of the string is used to determine which base to parse: those starting with 0x are parsed in hexadecimal, and those starting with 0 It is parsed in octal format, and the others are parsed in decimal format.

Parse "-42" in decimal mode and save it as int64 type:

i, _ := strconv.ParseInt("-42", 10, 

64)

Parse "23" in quinary mode and save it as int64 type:

i, _ := strconv.ParseInt("23", 5, 64)
println(i)    // 13

Because in 5-digit system, 23 means carrying twice and adding 3, so the corresponding decimal number is 5*2 3=13.

Parse 23 in hexadecimal and save it as int64 type:

i, _ := strconv.ParseInt("23", 16, 64)
println(i)    // 35

Because in hexadecimal, 23 means carrying 2 times and adding 3, so the corresponding decimal number is 16 *2 3=35.

Parse 23 in hexadecimal and save it as int64 type:

i, _ := strconv.ParseInt("23", 15, 64)
println(i)    // 33

Because in hexadecimal, 23 means carrying 2 times and adding 3, so the corresponding decimal number is 15 *2 3=33.

Format class function

Format the given type into 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) string
func FormatUint(i uint64, base int) string

The second parameter base specifies the base to convert the first parameter to. The valid value is 2<=base< ;=36. when specifying When the base digit of is greater than 10, the value exceeding 10 is represented by letters a-z. For example, in hexadecimal, the numbers 10-15 are used respectively a-f means that in hexadecimal system, values ​​10-16 are represented by a-g respectively.

For example: FormatInt(-42, 16) means converting -42 into a hexadecimal number, and the conversion result is -2a.

FormatFloat() has many parameters:

func FormatFloat(f float64, fmt byte, prec, 

bitSize int) string

bitSize表示f的来源类型(32:float32、64:float64),会据此进行舍入。

fmt表示格式:'f'(-ddd.dddd)、'b'(-ddddp±ddd,指数为二进制) 、'e'(-d.dddde±dd,十进制指数)、'E'(-d.ddddE±dd,十进制指数)、 'g'(指数很大时用'e'格式,否则'f'格式)、'G'(指数很 大时用'E'格式,否则'f'格式)。

prec控制精度(排除指数部分):对'f'、'e'、'E',它表示小 数点后的数字个数;对'g'、'G',它控制总的数字个数。如果prec 为-1,则 代表使用最少数量的、但又必需的数字来表示f。

Append类函数

AppendTP类函数用于将TP转换成字符串后append到一个slice中:AppendBool()、 AppendFloat()、AppendInt()、AppendUint()。

Append类的函数和Format类的函数工作方式类似,只不过是将转换后的结果追加到一个 slice中。

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // 声明一个slice
    b10 := []byte("int (base 10):")
    
    // 将转换为10进制的string,追加到slice中
    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))
}

输出结果:

int (base 10):-42
int (base 16):-2a

更多golang知识请关注golang教 程栏目。

The above is the detailed content of Go language data type conversion tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete