Home Backend Development Golang Go language data type conversion tutorial

Go language data type conversion tutorial

Dec 30, 2019 pm 05:49 PM
go language

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)
Copy after login

For example:

// 浮点数
a := 5.0

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

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)
Copy after login

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")
Copy after login

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
Copy after login

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
Copy after login

2. Convert string to int: Atoi()

func Atoi(s string) (int, error)
Copy after login

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")
}
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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

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

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
Copy after login

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
Copy after login

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)
Copy after login

FormatInt() and FormatUint() have two parameters:

func FormatInt(i int64, base int) string
func FormatUint(i uint64, base int) string
Copy after login

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
Copy after login

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))
}
Copy after login

输出结果:

int (base 10):-42
int (base 16):-2a
Copy after login

更多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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles