How to Avoid Type Assertions in Type Switch Branches
In Go, type switches are commonly used to handle objects of different types. However, manually asserting the type of an object within each case can become tedious. This question addresses the issue of eliminating the need for such assertions.
Original Question:
I use type switches like the following:
switch question.(type) { case interfaces.ComputedQuestion: handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols) case interfaces.InputQuestion: handleInputQuestion(question.(interfaces.InputQuestion), symbols) }
Is there a way to prevent the explicit type assertion inside the cases?
Answer:
Yes, you can avoid type assertions by assigning the result of the type switch to a variable of the expected type. This gives you the asserted type without the need for further assertions.
switch question := question.(type) { case interfaces.ComputedQuestion: handleComputedQuestion(question, symbols) case interfaces.InputQuestion: handleInputQuestion(question, symbols) }
In this example, the question := question.(type) expression assigns the result of the type switch to the question variable. The type switch itself remains unchanged.
This approach simplifies your code by eliminating the need for manual type assertions within the cases, making it more concise and easier to read.
The above is the detailed content of How Can I Avoid Type Assertions in Go's Type Switch Cases?. For more information, please follow other related articles on the PHP Chinese website!