Golang丰富的I/O----用N种Hello World展示

Golang是我目前用过的最好的语言,一接触便深深地喜爱,不断实践,喜爱之情日久弥深。原因之一便是简单、强大、易用。编程操作涉及频率最高的莫过于I/O,标准io包提供的两个接口(io.Reader和io.Writer)对I/O进行了伟大的统一抽象,将简单、强大、易用的特点体现地淋漓尽致。两个接口的定义如下:

typeReaderinterface {

    Read(p []byte) (n int, err error)

}

typeWriterinterface {

    Write(p []byte) (n int, err error)

}

  

标准库中的多个包实现了这两个接口,从而提供了丰富而强大的I/O功能。下面用N种输出“Hello,world!”来感受下。

package main

import (

    "bufio"

    "bytes"

    "fmt"

    "io"

    "log"

    "mime/quotedprintable"

    "os"

    "strings"

    "text/tabwriter"

)

func main() {

    //1

    fmt.Println("hello, world!")

    //2

    io.WriteString(os.Stdout, "Hello, World!\r\n")

    os.Stdout.WriteString("Hello, World!\r\n")

    //3

    w := bufio.NewWriter(os.Stdout)

    fmt.Fprint(w, "Hello, ")

    fmt.Fprint(w, "world!\r\n")

    w.Flush() // Don't forget to flush!

    fmt.Fprint(os.Stdout, "hello, world!\r\n")

    //4

    r := strings.NewReader("hello, world!\r\n")

    if _, err := io.Copy(os.Stdout, r); err != nil {

        log.Fatal(err)

    }

    r1 := strings.NewReader("hello, world!\r\n")

    buf := make([]byte, 8)

    // buf is used here...

    if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {

        log.Fatal(err)

    }

    r2 := strings.NewReader("hello, world!\r\n")

    //buf := make([]byte, 8)

    if _, err := io.CopyN(os.Stdout, r2, int64(r2.Len())); err != nil {

        log.Fatal(err)

    }

    //5

    var b bytes.Buffer // A Buffer needs no initialization.

    b.Write([]byte("Hello, "))

    fmt.Fprintf(&b, "world!\r\n")

    b.WriteTo(os.Stdout)

    // Output: Hello world!

    //6

    wTab := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', tabwriter.AlignRight)

    defer wTab.Flush()

    wTab.Write([]byte("Hello, world!\r\n"))

    //7

    wQuote := quotedprintable.NewWriter(os.Stdout)

    wQuote.Write([]byte("Hello, world!\r\n"))

    wQuote.Write([]byte("These symbols will be escaped: = \t"))

    wQuote.Close()

    wQuote.Write([]byte("\r\n"))

    //8

    log := log.New(os.Stdout, "", 0)

    log.Println("Hello, world!")

}

  

以上代码均来自go源码,编译运行输出如下:

hello, world!

Hello, World!

Hello, World!

Hello, world!

hello, world!

hello, world!

hello, world!

hello, world!

Hello, world!

Hello, world!

Hello, world!

These symbols will be escaped: =3D =09

Hello, world!

  

第一种很常见,

fmt.Println("hello, world!")

  

各种go语言书籍中均展示了该种形式的Hello World。

第二种是io包和os包提供的WriteString函数或方法,对io.Writer进行了封装。

第三种是fmt包提供的Fprint函数,与第一种类似。从go源码可以看出Print和Println分别是对Fprint和Fprintln函数的封装。

func Print(a ...interface{}) (n int, err error) {

    return Fprint(os.Stdout, a...)

}

func Println(a ...interface{}) (n int, err error) {

    return Fprintln(os.Stdout, a...)

}

  

第四种是io包提供的三个copy函数:io.Copy、io.CopyBuffer和io.CopyN。这三个函数是对copyBuffer函数的封装,

// copyBuffer is the actual implementation of Copy and CopyBuffer.

// if buf is nil, one is allocated.

func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)

  

copyBuffer函数借助buf缓冲从Reader读取数据然后写入到Writer中。

第五种是bytes包提供的方法,对Writer方法进行了封装。

// WriteTo writes data to w until the buffer is drained or an error occurs.

// The return value n is the number of bytes written; it always fits into an

// int, but it is int64 to match the io.WriterTo interface. Any error

// encountered during the write is also returned.

func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)

  

第六种是text包实现的io.Writer接口,text/tabwriter包可以实现文本列对齐输出。

// Write writes buf to the writer b.

// The only errors returned are ones encountered

// while writing to the underlying output stream.

//

func (b *Writer) Write(buf []byte) (n int, err error) {

  

第七种是"mime/quotedprintable"包实现的io.Writer接口。

// Write encodes p using quoted-printable encoding and writes it to the

// underlying io.Writer. It limits line length to 76 characters. The encoded

// bytes are not necessarily flushed until the Writer is closed.

func (w *Writer) Write(p []byte) (n int, err error) {

  

第八种也是比较常用的,由log包提供的。

这么多种Hello
World的写法可能不是全面的,但这是我见过的写法最多的一种语言。

Golang丰富的I/O----用N种Hello World展示的更多相关文章

  1. golang中发送http请求的几种常见情况

    整理一下golang中各种http的发送方式 方式一 使用http.Newrequest 先生成http.client -> 再生成 http.request -> 之后提交请求:clie ...

  2. golang中获取字符串长度的几种方法

    一.获取字符串长度的几种方法   - 使用 bytes.Count() 统计   - 使用 strings.Count() 统计   - 将字符串转换为 []rune 后调用 len 函数进行统计   ...

  3. golang的序列化与反序列化的几种方式

    golang用来序列化的模块有很多,我们来介绍3个. json 首先登场的是json,这个几乎毋庸置疑. 序列化 package main import ( "encoding/json&q ...

  4. Golang简单写文件操作的四种方法

    package main import ( "bufio" //缓存IO "fmt" "io" "io/ioutil" ...

  5. Golang- import 导入包的几种方式:点,别名与下划线

    包的导入语法 在写Go代码的时候经常用到import这个命令用来导入包文件,看到的方式参考如下: import( "fmt" ) 然后在代码里面可以通过如下的方式调用 fmt.Pr ...

  6. golang 开发 Struct 转换成 map 两种方式比较

    原文链接:https://www.jianshu.com/p/81c4304f6d1b 最近做Go开发的时候接触到了一个新的orm第三方框架gorose,在使用的过程中,发现没有类似beego进行直接 ...

  7. 解决 golang unrecognized import path "golang.org/x" 之类错误的一种尝试

    如果使用的开发IDE是goland,那么 打开 FILE -> setting -> Go Modules 选项 ,在proxy 选项上填写 "https://goproxy.i ...

  8. golang struct结构体初始化的几种方式

    type User struct { Id int `json:"id" orm:"auto"` // 用户名 Username string `json:&q ...

  9. [goa]golang微服务框架学习(三)-- 使用swagger-ui展示API

    既然goa框架自动生成啦swagger-json文件,那么如何用swagger-ui展示出来呢? 这里分三步: 1.下载swagger-ui的web代码 2.添加swagger.json 和 swag ...

随机推荐

  1. [阿里云部署] Ubuntu+Flask+Nginx+uWSGI+Mysql搭建阿里云Web服务器

    部署地址:123.56.7.181 Ubuntu+Flask+Nginx+uWSGI+Mysql搭建阿里云Web服务器 这个标题就比之前的"ECS服务器配置Web环境的全过程及参考资料&qu ...

  2. python requests抓取NBA球员数据,pandas进行数据分析,echarts进行可视化 (前言)

    python requests抓取NBA球员数据,pandas进行数据分析,echarts进行可视化 (前言) 感觉要总结总结了,希望这次能写个系列文章分享分享心得,和大神们交流交流,提升提升. 因为 ...

  3. java MD5比较文件内容

    最近用到,记下来…… 功能: 对指定目录下的所有TXT文件,通过MD5比较内容,删除掉重复的文件.文件的扩展可以修改成.docx..doc..jpg..png,或者其它类型,根据需求灵活修改. pub ...

  4. 自定义spring mvc的json视图

    场景 前端(安卓,Ios,web前端)和后端进行了数据的格式规范的讨论,确定了json的数据格式: { "code":"200", "data&quo ...

  5. 如何简单愉快的上手PipelineDB

    pipelineDB source:https://github.com/pipelinedb/pipelinedb 安装PipelineDB ./configure CFLAGS="-g ...

  6. Spring Cloud 自定义ConfigServer

    公司需要将系统配置信息中的敏感信息独立存放. 现有系统采用Spring Cloud Config提供配置信息,其中敏感信息主要是Db配置,分解本次需求: (1)数据库配置信息分离(主要是Db信息). ...

  7. HVR又一次load的时候须要将schedule suspend掉

    今天在进行HVR的又一次load的时候.报错了: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fi ...

  8. SSI学习(二)

    1.SSI指令 #config:指定返回到client浏览器的错误消息.日期和文件大小所使用的格式. #echo:在 HTML 页中插入环境变量的值. #exec:执行一个应用程序或一条 shell ...

  9. php之str_replace具体解释

    str_replace (PHP 4, PHP 5) str_replace - Replace all occurrences of the search string with the repla ...

  10. 怎样解决jsp:include标签在包括html文件时遇到的乱码问题

    在一个JSP页面中,经常须要包括还有一个文件,JSP为我们提供了jsp:include标签能够完毕这个功能,比方:<jsp:include page="some.jsp"&g ...