search
HomeBackend DevelopmentGolangGo 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)

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

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:博客园. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.