There is no implicit type conversion in golang. All type conversions must be explicitly declared with the syntax "valueOfTypeB = typeB(valueOfTypeA)". Type conversion can only be successful if the definition is correct. When converting from a type with a larger value range to a type with a smaller value range, precision loss (truncation) will occur.
The operating environment of this tutorial: windows10 system, GO 1.11.2, thinkpad t480 computer.
Go language data type conversion
Type conversion occurs when a value is converted from one type to another. Static languages such as c/c and Java provide implicit type conversion, but this is different for a strong type system like golang. Golang does not support automatic type conversion or implicit type conversion.
Since there is no implicit type conversion in Go language, all type conversions must be explicitly declared:
valueOfTypeB = typeB(valueOfTypeA)
means: The value of type B = type B (value of type A)
Example:
a := 5.0 b := int(a)
Type conversion can only be successful when the definition is correct, such as from a value with a smaller range Type conversion to a type with a larger value range (convert int16 to int32). Precision loss (truncation) occurs when converting from a type with a larger range to a type with a smaller range (converting int32 to int16 or float32 to int).
Only variables of the same underlying type can be converted to each other (such as converting the int16 type to the int32 type). Compilation errors will occur when variables of different underlying types are converted to each other (such as converting the bool type to the int type). ):
package main import ( "fmt" "math" ) func main() { // 输出各数值范围 fmt.Println("int8 range:", math.MinInt8, math.MaxInt8) fmt.Println("int16 range:", math.MinInt16, math.MaxInt16) fmt.Println("int32 range:", math.MinInt32, math.MaxInt32) fmt.Println("int64 range:", math.MinInt64, math.MaxInt64) // 初始化一个32位整型值 var a int32 = 1047483647 // 输出变量的十六进制形式和十进制值 fmt.Printf("int32: 0x%x %d\n", a, a) // 将a变量数值转换为十六进制, 发生数值截断 b := int16(a) // 输出变量的十六进制形式和十进制值 fmt.Printf("int16: 0x%x %d\n", b, b) // 将常量保存为float32类型 var c float32 = math.Pi // 转换为int类型, 浮点发生精度丢失 fmt.Println(int(c)) }
The code description is as follows:
Lines 11 to 14 output the numerical ranges of several common integer types.
Line 17, declare the variable a of type int32 and initialize it.
Line 19 uses the %x verb of fmt.Printf to output the value in hexadecimal format. This line outputs the 32-bit value of a before conversion.
Line 22, convert the value of a to int16 type, that is, convert from 32-bit signed integer type to 16-bit signed integer type. Due to the value range of int16 type The value range is smaller than the int32 type, so the value will be truncated (precision is lost).
Line 24 outputs the converted a variable value, which is the value of b, and is also printed in hexadecimal and decimal formats.
Line 27, math.Pi is a constant of the math package. It has no type by default. It will be automatically deduced based on the actual type where it is referenced. Here math.Pi is assigned to a variable. c, so the type is float32.
Line 29, convert float32 to int type and output.
The code output is as follows:
int8 range: -128 127 int16 range: -32768 32767 int32 range: -2147483648 2147483647 int64 range: -9223372036854775808 9223372036854775807 int32: 0x3e6f54ff 1047483647 int16: 0x54ff 21759 3
According to the output result, the range of 16-bit signed integer is -32768~32767, and the value of variable a, 1047483647, is not in this range Inside. The corresponding hexadecimal value of 1047483647 is 0x3e6f54ff. After converting to int16 type, the length is shortened by half, that is, it is cut in half in hexadecimal and becomes 0x54ff, and the corresponding decimal value is 21759.
When a floating point number is converted to an integer, the decimal part will be removed and only the integer part will be retained.
Type conversion practice
Practical combat 1
package main import ( "fmt" ) // 演示 golang 中基本数据类型的转换 func main() { var i int32 = 100 // 将 i => float var n1 float32 = float32(i) var n2 int8 = int8(i) var n3 int64 = int64(i) // 低精度 => 高精度 fmt.Printf("i=%v n1=%v n2=%v n3=%v \n", i, n1, n2, n3) // 被转换的是变量存储的数据(即值),变量本身的数据类型并没有变化 fmt.Printf("i type is %T\n", i) // int32 // 在转换中,比如将 int64 转成 int8 (-128---127) ,编译时不会报错, // 只是转换的结果是按溢出处理,和我们希望的结果不一样 var num1 int64 = 999999 var num2 int8 = int8(num1) fmt.Println("num2=", num2) }
Test result
i=100 n1=100 n2=100 n3=100 i type is int32 num2= 63
actual combat 2
package main import ( "fmt" _ "fmt" // 如果我们没有使用到一个包,但是有想去掉,前面加一个 _ 表示忽略 ) func main() { // 小练习 var n1 int32 = 12 var n2 int64 var n3 int8 // n2 = n1 + 20 // int32 ---> int64 错误 // n3 = n1 + 20 // int32 ---> int8 错误 n2 = int64(n1) + 20 // 正确 n3 = int8(n1) + 20 // 正确 fmt.Println("n2=", n2, "n3=", n3) }
test result
n2= 32 n3= 32
actual combat 3
package main import ( "fmt" _ "fmt" // 如果我们没有使用到一个包,但是有想去掉,前面加一个 _ 表示忽略 ) func main() { var n1 int32 = 12 var n3 int8 var n4 int8 n4 = int8(n1) + 127 // 编译通过,但是结果 不是 127+12 ,按溢出处理 n3 = int8(n1) + 128 // 编译不过 fmt.Println(n4, n3) }
test result
# command-line-arguments .\main.go:23:16: constant 128 overflows int8
For more programming-related knowledge, please visit: programming video! !
The above is the detailed content of How to perform data type conversion in golang. For more information, please follow other related articles on the PHP Chinese website!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

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.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment