在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錯誤。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.PipeWriter.Write() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。