温馨提示×

go结构体强制类型转换的方法是什么

go
小亿
96
2023-08-07 23:54:47
栏目: 编程语言

在Go语言中,结构体之间的强制类型转换需要使用类型断言。类型断言的语法如下:

value, ok := expression.(Type)

其中,expression是要转换的变量,Type是目标类型。ok是一个布尔值,用于判断转换是否成功。

下面是一个示例:

type Circle struct {
radius float64
}
type Rectangle struct {
width  float64
height float64
}
func main() {
var shape interface{}
// 创建一个Circle类型的变量
shape = Circle{radius: 5.0}
// 将shape强制转换为Circle类型
if circle, ok := shape.(Circle); ok {
fmt.Printf("Circle radius: %.2f\n", circle.radius)
} else {
fmt.Println("Not a Circle")
}
// 将shape强制转换为Rectangle类型
if rectangle, ok := shape.(Rectangle); ok {
fmt.Printf("Rectangle width: %.2f, height: %.2f\n", rectangle.width, rectangle.height)
} else {
fmt.Println("Not a Rectangle")
}
}

在上面的示例中,我们先创建了一个空接口变量shape,然后将其赋值为Circle类型的变量。接着通过类型断言将shape强制转换为Circle类型,并打印出radius字段的值。由于shape实际上是一个Circle类型的变量,所以类型断言成功,打印出了radius字段的值。然后我们尝试将shape强制转换为Rectangle类型,由于shape实际上不是Rectangle类型的变量,所以类型断言失败,打印出了"Not a Rectangle"。

0