在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"。