缓冲的通道工作人员恐慌

I wrote a little worker queue using buffered channels. I want to have the ability to "restart" this worker.

But when I do so I get a panic saying "panic: close of closed channel".

Actually I don't understand why its a closed channel because it shouldn't be closed any more after the make.

Here is the example code (http://play.golang.org/p/nLvNiMaOoA):

package main

import (
    "fmt"
    "time"
)

type T struct {
    ch chan int
}

func (s T) reset() {
    close(s.ch)
    s.ch = make(chan int, 2)
}

func (s T) wrk() {
    for i := range s.ch {
        fmt.Println(i)
    }
    fmt.Println("close")
}

func main() {
    t := T{make(chan int, 2)}
    for {
        go t.wrk()
        time.Sleep(time.Second)
        t.reset()
    }
}

Can you tell me what I'm doing wrong there?

The problem is that you have a value receiver in your reset function which means that s will be copied and you don't see the effects on your t variable in the loop.

To fix that, make it a pointer receiver:

func (s *T) reset() {
    close(s.ch)
    s.ch = make(chan int, 2)
}

For more info on this topic see Effective Go.