#What does the `thing.(*otherThing)` syntax mean?
7 messages · Page 1 of 1 (latest)
It's type assertion
It's different from casting/conversion
The former tells the value which is in some sort of interfaces "you're actually that type!
The latter simply changes the type
Ok, so you would do that to an interface, if you know the exact type?
What happens if it is not the correct type?
There's two patterns to validate the type:
- check the cast response
if obj, ok := o.(*widget.Lable); ok !{
obj.SetText(data[i])
} else {
slog.Warn("Invalid object type received")
}
- Switch statements:
var x interface{} = 2.3
switch v := x.(type) {
case int:
fmt.Println("int:", v)
case float64:
fmt.Println("float64:", v)
default:
fmt.Println("unknown")
}
both provide a higher level of safety to avoid panics if you get in the wrong types
Thank you! I didn't know you could switch on types. In the case described in the documentation, the type should be known
Kind of? You can determine the type using reflection but that's really not a route you likely want to take.
var err error
t := reflect.TypeOf(&err).Elem()