乐闻世界logo
搜索文章和话题

What is type assertion in Golang?

1个答案

1

Type assertion is a feature in Go that enables extracting the concrete value from an interface variable. In Go, interface types are variables that can hold values of any type, and type assertion allows retrieving the dynamic type information of an interface variable.

The basic syntax is as follows:

go
value, ok := interfaceVariable.(Type)

Here, interfaceVariable is an interface variable, and Type is the type to which we are asserting. This statement returns two values: value holds the value of the asserted type if the assertion succeeds, and ok is a boolean that is true when the assertion succeeds and false otherwise.

For example, suppose we have an interface Animal with multiple implementations, such as Dog and Cat. Here's how to use type assertion to determine the concrete type of an Animal interface variable:

go
type Animal interface { Speak() string } type Dog struct { } func (d Dog) Speak() string { return "Woof" } type Cat struct { } func (c Cat) Speak() string { return "Meow" } func identifyAnimal(a Animal) { if dog, ok := a.(Dog); ok { fmt.Println("This is a Dog, it says:", dog.Speak()) } else if cat, ok := a.(Cat); ok { fmt.Println("This is a Cat, it says:", cat.Speak()) } else { fmt.Println("Unknown Animal") } } func main() { var a Animal a = Dog{} identifyAnimal(a) a = Cat{} identifyAnimal(a) }

In this example, the identifyAnimal function uses type assertion to check the concrete type of the Animal interface variable a. Based on the result of the type assertion, the function prints the corresponding information. This is a practical application of type assertion in real-world scenarios: executing different logic based on the type.

2024年8月7日 21:47 回复

你的答案