How to use type assertions for type conversion in golang

PHPz
Release: 2024-05-01 15:45:01
Original
516 people have browsed it

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)
Copy after login

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}
}
Copy after login

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)
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!