Golang 中的类型转换


2022年1月15日, Learn eTutorial
2024

在本教程中,您将学习 Golang 中可用的不同转换类型。Golang 支持字符串、整数、布尔值、浮点数等不同类型的数据类型。不同类型的转换会导致不同的结果。

Golang 中的类型转换是什么?

类型转换是将任何已定义数据类型的变量转换为另一种数据类型变量的过程。例如将数据类型 int 转换为 float(4 转换为 4.0),float 转换为 int(4.0 转换为 4)等。
有两种类型的转换

  1.   隐式
    • 从一种数据类型自动转换为另一种数据类型。
    • 数据类型由编译器转换。
    • 也称为类型转换。
  2.   显式
    • 用户手动显式执行数据类型转换。
    • 程序员使用强制转换运算符将数据类型转换为另一种数据类型。
    • 也称为类型强制转换。
GO : Type-casting

Golang 中为什么需要类型转换?

Go 编程语言不支持自动类型转换。考虑两个声明为整数数据类型的数字执行加法后的结果不能存储在声明为浮点类型的变量中。这意味着 Golang 是一种严格类型语言,变量在将任何值赋给变量之前必须转换为所需的数据类型。

Golang 支持显式类型转换;用户需要手动转换任何变量的类型。

让我们考虑一个示例来理解类型转换的必要性。
 


package main
import "fmt"

func main() {

var a  int = 25
var b int = 25
var result float32
result = a+b
fmt.Println("The result after addition is ", result)

}

输出


_/home/0ax1ZC
./prog.go:10:8: cannot use a + b (type int) as type float32 in assignment

对于上述代码,结果输出显示一些错误,这表明整数类型的 a 和 b 不能分配给 float32 类型的变量。

GO : Type-casting

让我们看看如何将 int 类型的结果转换为 float,以便可以将其存储在声明的变量 result 中。代码 result = float32(a)+float32(b) 转换为结果输出格式。

示例


package main
import "fmt"
 
func main() {
 
    // taking the required data into variables
    var num1 int = 846
    var num2 int = 19
    var sum float32
 
    // explicit type conversion
    sum = float32(num1) + float32(num2)
 
    // Displaying the result
    fmt.Printf("Result = %f\n,Type = %T\n", sum,sum)
}

输出


Result = 865.000000
,Type = float32

注意:Golang 不支持自动类型转换或隐式类型转换。

Golang 中类型转换的语法是什么?

遵循的基本转换语法如下


<varaiable name> := <datatype_name >(value of other type to convert)

注意:Go 支持显式类型转换

即,类型转换由 Java 编译器“自动”执行,而“类型强制转换”(使用强制转换运算符)则需要 Java 程序员显式执行。它通常分为两类
让我们通过一个例子来理解

GO : Type-casting

package main

import (
"fmt"
)

func main() {
var a int = 4 // integer number 4
f := float64(a)
fmt.Println("datatype of int type converted to float type ", f)
fmt.Printf("Type = %T\n",f)

}

输出


datatype of int type converted to float type  4
Type = float64

在上面的示例中,声明了一个值为 4 的整数数据类型变量,该变量通过使用上述语法转换为浮点数据类型。