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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同