Golang豐富的I/O----用N種Hello World展示

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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 mainimport (    "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 =09Hello, 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包提供的。



這麼多種HelloWorld的寫法可能不是全面的,但這是我見過的寫法最多的一種語言。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.