首页 > 解决方案 > bufio.NewScanner 的重置方法?

问题描述

有没有办法重置 *Scanner(来自 bufio.NewScanner)或清除旧令牌?不幸的是,“func (b *Reader) Reset(r io.Reader)”不适用于 *Scanner。

更新/澄清: 我想在“time.Sleep(30 * time.Second)”结束时使用 os.Stdout 中的最新数据继续,并跳过这 30 秒内可以读取的所有数据。

我目前正在使用 for 循环作为肮脏的解决方法:

scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
    fmt.Println(scanner.Text())

    if scanner.Text() == "abc" {
        //do something that takes a little time
        time.Sleep(30 * time.Second)

        // my dirty workaround:
        // skips all old tokens/inputs
        for skip := time.Now(); time.Since(skip).Seconds() < 10; {
            scanner.Scan()
        }
    }
}

标签: go

解决方案


在 goroutine 中运行 long 操作。在 goroutine 运行时丢弃输入。

scanner := bufio.NewScanner(os.Stdout)
var discard int32
var wg sync.WaitGroup
for scanner.Scan() {
    if atomic.LoadInt32(&discard) != 0 {
        continue
    }

    fmt.Println(scanner.Text())

    if scanner.Text() == "abc" {
        atomic.StoreInt32(&discard, 1)
        wg.Add(1)
        go func() {
            defer wg.Done()
            defer atomic.StoreInt32(&discard, 0)
            //do something that takes a little time
            time.Sleep(30 * time.Second)
        }()
    }
}

wg.Wait() // wait for long process after EOF or error.

推荐阅读