How to implement type conversion in interfaces in Go?
In Go language, you can use type assertion .(Type) or Type.(interface) to perform interface type conversion.
- (Type)
var i interface{} = "Hello"
s := i.(string)
fmt.Println(s) // Output: Hello
n, ok := i.(int)
fmt.Println(n, ok) // Output: 0 false
- Category (interface)
var s string = "Hello"
i := interface{}(s)
fmt.Println(i) // Output: Hello
It is important to note that asserting or converting failure can lead to runtime errors, so it is best to use type assertion to determine if an interface can be converted to a specific type before performing type conversions. You can use the blank identifier _ to ignore unnecessary return values.
var i interface{} = 42
if s, ok := i.(string); ok {
fmt.Println(s) // Output: 42
} else {
fmt.Println("Conversion failed")
}
Furthermore, you can also use a switch statement for asserting multiple types.
var i interface{} = 42
switch v := i.(type) {
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}
The above code will handle i differently based on its type. If i is of type int, it will output “Integer: 42”; if i is of type string, it will output “String: 42”; otherwise, it will output “Unknown type”.