Home > Backend Development > Golang > How Can I Avoid Type Assertions Inside Go's Type Switch Branches?

How Can I Avoid Type Assertions Inside Go's Type Switch Branches?

Susan Sarandon
Release: 2024-12-06 09:21:11
Original
894 people have browsed it

How Can I Avoid Type Assertions Inside Go's Type Switch Branches?

Eliminating Type Assertions within Type Switch Branches

In Go, type switches provide a convenient means of branching execution based on the type of a value. However, type assertions within these branches can become repetitive and cumbersome.

Type Assertion Avoidance

To avoid unnecessary type assertions, you can assign the result of the type switch to a typed variable:

switch question := question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question, symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question, symbols)
}
Copy after login
Copy after login

In this example, the type switch assigns the value of question to the variable question, which is automatically typed according to the branch that executes. This eliminates the need for explicit type assertions within the branches.

Example

Consider the following code:

switch question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question.(interfaces.ComputedQuestion), symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question.(interfaces.InputQuestion), symbols)
}
Copy after login

Replacing the type assertions with variable assignments yields the following equivalent code:

switch question := question.(type) {
case interfaces.ComputedQuestion:
    handleComputedQuestion(question, symbols)
case interfaces.InputQuestion:
    handleInputQuestion(question, symbols)
}
Copy after login
Copy after login

By adopting this approach, you can streamline your code and improve its readability without sacrificing functionality.

The above is the detailed content of How Can I Avoid Type Assertions Inside Go's Type Switch Branches?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template