Home > OS >  How to correct save function handler in structure?
How to correct save function handler in structure?

Time:10-24

I try to initialize function in structure.

package main

import "fmt"

type Handler struct {
    name    string
    handler func()
}

func (h *Handler) Emit() {
    h.handler()
}

func main() {
    var handlers []*Handler

    for i := 0; i < 5; i   {
        handler := func() {
            fmt.Printf("There is %d\n", i)
        }
        handlers = append(handlers, &Handler{
            name:    fmt.Sprintf("handler_%d", i),
            handler: handler,
        })
    }

    for i := 0; i < 5; i   {
        fmt.Println(handlers[i].name)
        handlers[i].Emit()
    }
}

But, I've got passing only last pointer (instance) of func. Output:

handler_0
There is 5
handler_1
There is 5
handler_2
There is 5
handler_3
There is 5
handler_4
There is 5

CodePudding user response:

When you are in a loop, i is always the same variable withe a different value so i = 5 for all the handlers when you finish the loop. for correct that, create a new variable equal to i in the for :

for i := 0; i < 5; i   {
    loop_i := i
    handler := func() {
        fmt.Printf("There is %d\n", loop_i)
    }
    handlers = append(handlers, &Handler{
        name:    fmt.Sprintf("handler_%d", loop_i),
        handler: handler,
    })
}
  •  Tags:  
  • go
  • Related