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. 【微服务】之三:从零开始,轻松搞定SpringCloud微服务-配置中心

    在整个微服务体系中,除了注册中心具有非常重要的意义之外,还有一个注册中心.注册中心作为管理在整个项目群的配置文件及动态参数的重要载体服务.Spring Cloud体系的子项目中,Spring Clou ...

  2. PAT 1008. Elevator (20)

    1008. Elevator (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue The highest ...

  3. CCF-201312-1-出现次数最多的数

    问题描述 试题编号: 201312-1 试题名称: 出现次数最多的数 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 给定n个正整数,找出它们中出现次数最多的数.如果这样的数有 ...

  4. 魔术常量(Magic constants)

    魔术常量(Magic constants) PHP中的常量大部分都是不变的,但是有8个常量会随着他们所在代码位置的变化而变化,这8个常量被称为魔术常量. __LINE__,文件中的当前行号 __FIL ...

  5. 下拉菜单被挡住了,DIV置于最底层的方法

    网站常会用到一些 下拉菜单,,幻灯片,,,飘浮广告等. 但经常会发现.幻灯片会挡住下拉菜单或者飘浮广告等.解决办法有下 第一,可将幻灯片所在DIV 置于最底层.添加CSS如下 style=" ...

  6. [Docker基础]Docker安装教程

    Install Docker Docker支持几乎所有的Linux发行版,也支持Mac和Windows. 各操作系统的安装方法可参考Docker官网. 安装环境 ubuntu 16.04 Docker ...

  7. 基于DevExpress的BandedGridView动态生成多行(复合)表头

    最近cs项目中有个看板的功能需求,整个系统是基于DevExpress组件开发的,由于对这个组件的布局不是很熟,也借鉴了网上一些其他人的做法,普遍都是通过GridControl的BandedGridVi ...

  8. 1.5 sleep()方法

    方法sleep()的作用是在指定的毫秒数内让当前"正在执行的线程"休眠(暂停执行).这个"正在执行的线程"是指this.currentThread()返回的线程 ...

  9. Android IntentService使用介绍以及源码解析

    版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.IntentService概述及使用举例 IntentService内部实现机制用到了HandlerThread,如果对HandlerThrea ...

  10. Python字符串和日期相互转换的方法

    import time,datetime # 日期转换成字符串 print time.strftime("%Y-%m-%d %X", time.localtime()) #字符串转 ...