I know the Stop
function can not close the channel. I am just confused with the two different results of tickerTest1
and tickerTest2
.
package main
import (
"time"
"log"
)
func tickerTest1() {
ticker := *time.NewTicker(time.Second)
count := 0
go func() {
time.Sleep(3*time.Second)
ticker.Stop()
}()
for range ticker.C {
count ++
log.Println("tickerTest1:", count)
}
}
func tickerTest2() {
ticker := time.NewTicker(time.Second)
count := 0
go func() {
time.Sleep(3*time.Second)
ticker.Stop()
}()
for range ticker.C {
count ++
log.Println("tickerTest2:", count)
}
}
func main() {
go tickerTest1()
tickerTest2()
}
tickerTest2()
works as expected, so let's examine tickerTest1()
.
time.NewTicker()
returns a pointer value, a value of type *time.Ticker
. This already hints you should use it as that: as a pointer (and should not dereference it).
Yet, you dereference it by using the indirection operator:
ticker := *time.NewTicker(time.Second)
By dereferencing it,ticker
will be of type time.Ticker
, a non-pointer type. And its value will be a copy of the value pointed by the pointer that NewTicker()
returns.
This alone wouldn't be a problem, because Go automatically takes the address of ticker
whenever you call a method with pointer receiver on it (such as Ticker.Stop()
). But the address that is passed as the receiver will be the address of this ticker
variable, and any method that modifies the time.Ticker
struct will only modify this distinct copy, and not the time.Ticker
value that is pointed by the return value of the NewTicker()
function.
So in effect, you only stop the copy Ticker
stored in the ticker
variable, and not the original Ticker
that was returned by NewTicker()
and which is actually sending the values on the channel. That remains unstopped.