當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang io.MultiWriter()用法及代碼示例

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的MultiWriter()函數用於創建寫入器,該寫入器將其寫入複製到每個給定的寫入器中,這與Unix命令tee(1)相同。在這裏,每一次寫入均被逐一寫入每個包含的寫入器中。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

func MultiWriter(writers ...Writer) Writer

在此,“writers”是在此函數中指定為參數的寫入程序數。

返回值:它返回一個Writer,其中包括指定緩衝區中存在的字節數,並且還返回錯誤(如果有)。而且,如果聲明的寫手返回錯誤,則整個寫操作將停止並且不會擴展到列表的下方。

範例1:



// Golang program to illustrate the usage of 
// io.MultiWriter() function 
  
// Including main package 
package main 
  
// Importing fmt, io, bytes, and strings 
import ( 
    "bytes"
    "fmt"
    "io"
    "strings"
) 
  
// Calling main 
func main() { 
  
    // Defining reader using NewReader method 
    reader:= strings.NewReader("Geeks") 
  
    // Defining two buffers 
    var buffer1, buffer2 bytes.Buffer 
  
    // Calling MultiWriter method with its parameters 
    writer:= io.MultiWriter(&buffer1, &buffer2) 
  
    // Calling Copy method with its parameters 
    n, err:= io.Copy(writer, reader) 
  
    // If error is not nil then panics 
    if err != nil { 
        panic(err) 
    } 
  
    // Prints output 
    fmt.Printf("Number of bytes in the buffer:%v\n", n) 
    fmt.Printf("Buffer1:%v\n", buffer1.String()) 
    fmt.Printf("Buffer2:%v\n", buffer2.String()) 
}

輸出:

Number of bytes in the buffer:5
Buffer1:Geeks
Buffer2:Geeks

在此,Copy()方法用於返回緩衝區中包含的字節數。並且這裏兩個緩衝區的內容都與聲明的寫程序將其寫操作複製到所有其他寫程序相同。

範例2:

// Golang program to illustrate the usage of 
// io.MultiWriter() function 
  
// Including main package 
package main 
  
// Importing fmt, io, bytes, and strings 
import ( 
    "bytes"
    "fmt"
    "io"
    "strings"
) 
  
// Calling main 
func main() { 
  
    // Defining reader using NewReader method 
    reader:= strings.NewReader("GeeksforGeeks\nis\na\nCS-Portal!") 
  
    // Defining two buffers 
    var buffer1, buffer2 bytes.Buffer 
  
    // Calling MultiWriter method with its parameters 
    writer:= io.MultiWriter(&buffer1, &buffer2) 
  
    // Calling Copy method with its parameters 
    n, err:= io.Copy(writer, reader) 
  
    // If error is not nil then panics 
    if err != nil { 
        panic(err) 
    } 
  
    // Prints output 
    fmt.Printf("Number of bytes in the buffer:%v\n", n) 
    fmt.Printf("Buffer1:%v\n", buffer1.String()) 
    fmt.Printf("Buffer2:%v\n", buffer2.String()) 
}

輸出:

Number of bytes in the buffer:29
Buffer1:GeeksforGeeks
is
a
CS-Portal!
Buffer2:GeeksforGeeks
is
a
CS-Portal!



相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.MultiWriter() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。