snippetgoCritical
How to determine an interface{} value's "real" type?
Viewed 0 times
howdetermineinterfacevaluetypereal
Problem
I have not found a good resource for using
Do you know of a good introduction to using Go's
specific questions:
convert a value?
interface{} types. For examplepackage main
import "fmt"
func weirdFunc(i int) interface{} {
if i == 0 {
return "zero"
}
return i
}
func main() {
var i = 5
var w = weirdFunc(5)
// this example works!
if tmp, ok := w.(int); ok {
i += tmp
}
fmt.Println("i =", i)
}Do you know of a good introduction to using Go's
interface{}?specific questions:
- how do I get the "real" Type of w?
- is there any way to get the string representation of a type?
- is there any way to use the string representation of a type to
convert a value?
Solution
Your example does work. Here's a simplified version.
It uses Type assertions.
package main
import "fmt"
func weird(i int) interface{} {
if i < 0 {
return "negative"
}
return i
}
func main() {
var i = 42
if w, ok := weird(7).(int); ok {
i += w
}
if w, ok := weird(-100).(int); ok {
i += w
}
fmt.Println("i =", i)
}
Output:
i = 49It uses Type assertions.
Code Snippets
package main
import "fmt"
func weird(i int) interface{} {
if i < 0 {
return "negative"
}
return i
}
func main() {
var i = 42
if w, ok := weird(7).(int); ok {
i += w
}
if w, ok := weird(-100).(int); ok {
i += w
}
fmt.Println("i =", i)
}
Output:
i = 49Context
Stack Overflow Q#6372474, score: 123
Revisions (0)
No revisions yet.