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.
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
value
will be set to nil
and ok
will be set to false
. 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!