douzun4443 2017-08-17 17:07
浏览 35
已采纳

永无止境的Golang股票行情仅可播放2次

I'm trying to make a channel with never ending ticker, but it works only 2 times.

Could you help me to understand where is the problem?

Code:

package main 

import (
"fmt"
"time"
) 

var mark = [2]float64{8.9876, 762.098568}

func tick(out chan <- [2]float64){

    c := time.NewTicker(time.Millisecond *500)
    for range c.C{
        out <- mark
    }
}

func main() {

    fmt.Println("Start")

    md := make(chan [2]float64)
    go tick(md)

    for range <-md{
        fmt.Println(<-md)
    }
}

Output:

Start
[8.9876 762.098568]
[8.9876 762.098568]

Example: https://play.golang.org/p/P2FaUwbW-3

  • 写回答

1条回答 默认 最新

  • duanbai1974 2017-08-17 17:12
    关注

    This:

    for range <-md{
    

    is not the same as:

    for range md{
    

    The latter ranges over the channel (what you want), while the former ranges over the value received from the channel when the loop starts, which happens to be a two-element array, hence the two executions. You're also ignoring the value received from the channel in the for statement, and reading from it again in the loop body, ignoring every other message on the channel (though this makes no difference in the example, since every value is identical, it would make a significant difference in practice). What you really want is:

    for foo := range md{
        fmt.Println(foo)
    }
    

    Here's a working version of your playground example, slightly modified to avoid "program took too long" errors because in its current form it never stops: https://play.golang.org/p/RSUJFvluU5

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题