In Go, type assertion is a mechanism for obtaining the value of its concrete type from an interface type. This is very useful for handling values passed through the interface. Here are the basic concepts, syntax, and examples of type assertions.
1. Basic syntax
The syntax of type assertion is as follows:
value, ok := interfaceValue.(ConcreteType)
-
interfaceValue
is an interface type variable. -
ConcreteType
It is the specific type you expect. -
value
is the value of the specific type after a successful assertion. -
ok
is a Boolean value that indicates whether the assertion is successful.
2. Example
2.1 Typical usage
package main import ( "fmt" ) func main() { var i interface{} = "Hello, World!" // Type assertion s, ok := i.(string) if ok { ("String value:", s) // Output: String value: Hello, World! } else { ("Not a string") } }
2.2 Failed assertion
If the assertion fails,ok
Will befalse
,value
will be a zero value of this type.
package main import ( "fmt" ) func main() { var i interface{} = 42 s, ok := i.(string) if !ok { ("Not a string") // Output: Not a string } ("Value:", s) // Output: Value:}
2.3 Type checking using type assertions
Type assertions can be used to handle different concrete types:
package main import ( "fmt" ) func printType(i interface{}) { switch v := i.(type) { case string: ("String:", v) case int: ("Integer:", v) case float64: ("Float:", v) default: ("Unknown type") } } func main() { printType("Hello") printType(123) printType(3.14) printType(true) // Output: Unknown type}
3. Direct assertion
If you are sure that the value in the interface is a specific type, you can directly assert without checking.ok
:
package main import ( "fmt" ) func main() { var i interface{} = "Direct assertion" s := i.(string) // Direct assertion (s) // Output: Direct assertion // If the assertion fails, it will cause panic // i = 42 // s = i.(string) // Runtime error: interface conversion: interface {} is int, not string}
4. Summary
- Type AssertionUsed to extract specific types of values from the interface.
- use
value, ok := interfaceValue.(ConcreteType)
Syntax makes security assertions. - Can be used
switch
Statements deal with various types of situations. - Direct assertion may cause runtime errors. If you are not sure of the type, it is recommended to use a
ok
form.
Through type assertions, Go provides a flexible way to handle conversions of interface types and specific types.
This is the end of this article about the implementation example of golang type assertion. For more related golang type assertion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!