Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go行过滤器实例
Go行过滤器实例
作者:--    发布时间:2019-11-20

线过滤器是一种常见类型的程序,它读取stdin上的输入,处理它,然后将一些派生结果打印到stdoutgrepsed是常用的行过滤器。

这里是一个示例行过滤器,将写入所有输入文本转换为大写。可以使用此模式来编写自己的go行过滤器。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

line-filters.go的完整代码如下所示 -

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {

    // wrapping the unbuffered `os.stdin` with a buffered
    // scanner gives us a convenient `scan` method that
    // advances the scanner to the next token; which is
    // the next line in the default scanner.
    scanner := bufio.newscanner(os.stdin)

    for scanner.scan() {
        // `text` returns the current token, here the next line,
        // from the input.
        ucl := strings.toupper(scanner.text())

        // write out the uppercased line.
        fmt.println(ucl)
    }

    // check for errors during `scan`. end of file is
    // expected and not reported by `scan` as an error.
    if err := scanner.err(); err != nil {
        fmt.fprintln(os.stderr, "error:", err)
        os.exit(1)
    }
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run line-filters.go
this is a line filters demo by h3.com
this is a line filters demo by h3.com
yes
yes
no
no

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册