Integer type conversion in Go allows developers to convert values between different integer types. Type conversions include type casting (using () syntax) and type assertion (using type assertion syntax to check the actual type of a value). In actual combat scenarios, type conversion is used in applications such as operating different types of integer variables and converting file sizes.
Integer type conversion in Go
In the Go language, integer type conversion is a conversion between different integer types value process. It enables developers to manipulate data between different types of integer variables, providing code flexibility.
Type casting
There are two types of conversions in Go: type casting and type assertion. Type casting uses the ()
syntax to convert a value to another type. For example:
var a int32 = 10 var b int64 = int64(a) // 显式类型转换
With explicit type conversion, a
is converted to b
of type int64
.
Type assertion
Type assertion uses the type assertion
syntax to check the actual type of a value. It returns a Boolean value to indicate whether the conversion was successful and may return a converted value. For example:
var a interface{} = 10 b, ok := a.(int64) // 类型断言 if ok { fmt.Println("转换成功:", b) }
With type assertion, the interface value a
is checked to be b
of type int64
. If the conversion is successful, ok
is true
.
Practical case: read file size
The following is a practical case of reading file size, which shows the use of type conversion:
package main import ( "fmt" "os" ) func main() { f, err := os.Stat("file.txt") if err != nil { fmt.Println(err) return } sizeInBytes := f.Size() sizeInMB := float64(sizeInBytes) / (1024 * 1024) // 转换成 MB fmt.Printf("文件大小:%.2f MB\n", sizeInMB) }
In this case, type conversion is used to convert the file size from int64
(bytes) to float64
(megabytes) for display.
The above is the detailed content of Golang: Deep understanding of type conversion between integers. For more information, please follow other related articles on the PHP Chinese website!