I have a VBox widget that holds a dynamic amount of buttons which are loaded in from a database:
services, err := data.LoadServices(user)
if err != nil {
log.Println("Error while retrieving services,", err)
return widget.NewVBox()
}
serviceButtons := widget.NewVBox()
for _, service := range services {
serviceButtons.Append(
widget.NewButton(service.Name, func() {
log.Printf("button pressed, service: %s", service.Name)
}),
)
}
The buttons are displayed as expected, however when I click any of them, the tapped function of the last button is executed.
Unfortunately this is a subtlety of how Go assigns variables in a for loop. You need to include in the loop
capturedService := service
And then use capturedService In your print statement. This is because the access to the service variable is delayed until the callback executes and so it sees the last value for service.
Was struggling with this since I'm new to Go thanks for the information ^^
Most helpful comment
Unfortunately this is a subtlety of how Go assigns variables in a for loop. You need to include in the loop
capturedService := serviceAnd then use
capturedServiceIn your print statement. This is because the access to theservicevariable is delayed until the callback executes and so it sees the last value for service.