Home  >  Article  >  Backend Development  >  How to use type assertions for type conversion in golang

How to use type assertions for type conversion in golang

PHPz
PHPzOriginal
2024-05-01 15:45:01500browse

Type assertions in Go are used to convert interface values ​​to more specific types. It consists of the following steps: Declare the interface value and target type. Convert the interface value to the target type using type assertion syntax and assign the result to a variable. Use a boolean variable to check if the conversion was successful. If the conversion fails, the target variable will be set to nil.

golang 如何使用类型断言进行类型转换

Golang How to use type assertions for type conversion

Type assertions are a special operation in Go that allow us to convert an interface value to A more specific type. This is useful when working with untyped data or when you need to check variable types at runtime.

Syntax

The syntax of type assertion is as follows:

value, ok := value.(Type)

Where:

  • value is the interface value to be converted.
  • Type is the type we want to convert to.
  • ok is a Boolean value indicating whether the conversion is successful.

Practical case

Suppose we have an interface value i, which stores a Person structure :

type Person struct {
    Name string
    Age  int
}

func main() {
    i := Person{"John", 30}
}

If we want to convert i to Person type, we can use type assertion:

if person, ok := i.(Person); ok {
    fmt.Println(person.Name, person.Age)
}

If the conversion is successful, it will Assign person to the Person type, and ok to true. Otherwise, person will be set to nil and ok will be set to false.

Note

  • Type assertions can only be used for interface values.
  • If the type conversion fails, value will be set to nil and ok will be set to false.
  • When using type assertions, be sure to check the ok value to ensure the conversion was successful.

The above is the detailed content of How to use type assertions for type conversion in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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