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


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

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的PipeWriter.Write()函數用於實現Write的標準接口。它將信息寫入管道並阻塞它,直到一個讀取器或一個以上的讀取器接收了所有信息,或者關閉了管道的讀取端。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

func (w *PipeWriter) Write(data []byte) (n int, err error)

在這裏,“w”是指向PipeWriter的指針。其中PipeWriter是管道的寫入部分,而“data”是寫入數據的字節片。

返回值:它返回寫入的字節數和一個錯誤(如果有)。但是,如果管道的讀取端因錯誤而關閉,則該錯誤將作為err返回,否則返回的err為ErrClosedPipe錯誤。

範例1:



// Golang program to illustrate the usage of 
// io.pipeWriter.Write() function 
  
// Including main package 
package main 
  
// Importing fmt and io 
import ( 
    "fmt"
    "io"
) 
  
// Calling main 
func main() { 
  
    // Calling Pipe method 
    pipeReader, pipeWriter:= io.Pipe() 
  
    // Defining data parameter of Read method 
    data:= make([]byte, 20) 
  
    // Reading data into the buffer stated 
    go func() { 
        pipeReader.Read(data) 
  
        // Closing read half of the pipe 
        pipeReader.Close() 
    }() 
  
    // Using for loop 
    for i:= 0; i < 1; i++ { 
  
        // Calling pipeWriter.Write() method 
        n, err:= pipeWriter.Write([]byte("GfG!")) 
  
        // If error is not nil panic 
        if err != nil { 
            panic(err) 
        } 
  
        // Prints the content written 
        fmt.Printf("%v\n", string(data)) 
  
        // Prints the number of bytes 
        fmt.Printf("%v\n", n) 
    } 
}

輸出:

GfG!
4

在此,由於在“for”循環運行之前未關閉管道的讀取端,因此不會返回錯誤。

範例2:

// Golang program to illustrate the usage of 
// io.pipeWriter.Write() function 
  
// Including main package 
package main 
  
// Importing fmt and io 
import ( 
    "fmt"
    "io"
) 
  
// Calling main 
func main() { 
  
    // Calling Pipe method 
    pipeReader, pipeWriter:= io.Pipe() 
  
    // Defining data parameter of Read method 
    data:= make([]byte, 20) 
  
    // Reading data into the buffer stated 
    go func() { 
        pipeReader.Read(data) 
  
        // Closing read half of the pipe 
        pipeReader.Close() 
    }() 
  
    // Using for loop 
    for i:= 0; i < 2; i++ { 
  
        // Calling pipeWriter.Write() method 
        n, err:= pipeWriter.Write([]byte("GfG!")) 
  
        // If error is not nil panic 
        if err != nil { 
            panic(err) 
        } 
  
        // Prints the content written 
        fmt.Printf("%v\n", string(data)) 
  
        // Prints the number of bytes 
        fmt.Printf("%v\n", n) 
    } 
}

輸出:

GfG!
4
panic:io:read/write on closed pipe

goroutine 1 [running]:
main.main()
    /tmp/sandbox367087659/prog.go:38 +0x3ad

在此,在for循環的第一次迭代之後,由於關閉了管道的讀取端,因此返回了ErrClosedPipe錯誤。




相關用法


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