How to use a method as a goroutine function

Viewed 5806

I have this code. I expect to output:

hello : 1 
world : 2

but it outputs:

world : 2
world : 2

Is there something wrong with my code?

package main

import (
    "fmt"
    "time"
)

type Task struct {
    name string
    data int32
}

func (this *Task) PrintData() {
    fmt.Println(this.name, ":", this.data)
}

func main() {
    tasks := []Task{{"hello", 1}, {"world", 2}}
    for _, task := range tasks {
        go task.PrintData()
    }
    time.Sleep(time.Second * 5000)
}
2 Answers
Related