#What does the `thing.(*otherThing)` syntax mean?

7 messages · Page 1 of 1 (latest)

spare mesa
#

I was looking through the Fyne documentation, and I found this page. Where it uses the syntax:

o.(*widget.Label)

What does this syntax mean?

gritty stirrup
#

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

spare mesa
#

Ok, so you would do that to an interface, if you know the exact type?

#

What happens if it is not the correct type?

worthy tinsel
#

There's two patterns to validate the type:

  1. check the cast response
if obj, ok := o.(*widget.Lable); ok !{
   obj.SetText(data[i])
} else {
  slog.Warn("Invalid object type received")
}
  1. 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

spare mesa
#

Thank you! I didn't know you could switch on types. In the case described in the documentation, the type should be known

worthy tinsel
#

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()