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 关于#单片机#的问题:以ATMEGA128或相近型号单片机为控制器设计直流电机调速的闭环控制系统(相关搜索:设计报告|软件设计|流程图)
  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办