在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的Pipe()函數用於創建並發的in-memory管道,並且可以應用該函數來鏈接期望io.Reader的代碼與期望io.Writer的代碼。此處,管道上的讀取和寫入配對為one-to-one,除非需要多個“Reads”來獲取單個“Write”。這表示每次對PipeWriter的寫操作都停止,直到滿足了取自PipeReader的一個或多個Reads(完全讀取已寫入的數據)為止。
但是,數據是直接從寫入到相關讀取讀取的,內部沒有緩衝。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func Pipe() (*PipeReader, *PipeWriter)
此處,“PipeReader”是指向PipeReader的指針。其中PipeReader是管道的讀取部分,而“PipeWriter”是指向PipeWriter的指針。其中PipeWriter是管道的寫入部分。
返回值:它返回一個指向PipeReader和PipeWriter的指針。
注意:它可以同時或通過關閉來調用讀寫。但是,對Read的並行調用和對Write的並行調用也是安全的。單獨的調用將順序關閉。
範例1:
// Golang program to illustrate the usage of
// io.Pipe() function
// Including main package
package main
// Importing fmt, io, and bytes
import (
"bytes"
"fmt"
"io"
)
// Calling main
func main() {
// Calling Pipe method
pipeReader, pipeWriter:= io.Pipe()
// Using Fprint in go function to write
// data to the file
go func() {
fmt.Fprint(pipeWriter, "Geeks\n")
// Using Close method to close write
pipeWriter.Close()
}()
// Creating a buffer
buffer:= new(bytes.Buffer)
// Calling ReadFrom method and writing
// data into buffer
buffer.ReadFrom(pipeReader)
// Prints the data in buffer
fmt.Print(buffer.String())
}
輸出:
Geeks
範例2:
// Golang program to illustrate the usage of
// io.Pipe() function
// Including main package
package main
// Importing fmt, io, and bytes
import (
"bytes"
"fmt"
"io"
)
// Calling main
func main() {
// Calling Pipe method
pipeReader, pipeWriter:= io.Pipe()
// Using Fprint in go function to write
// data to the file
go func() {
fmt.Fprint(pipeWriter, "GeeksforGeeks\nis\na\nCS-Portal.\n")
// Using Close method to close write
pipeWriter.Close()
}()
// Creating a buffer
buffer:= new(bytes.Buffer)
// Calling ReadFrom method and writing
// data into buffer
buffer.ReadFrom(pipeReader)
// Prints the data in buffer
fmt.Print(buffer.String())
}
輸出:
GeeksforGeeks is a CS-Portal.
相關用法
- 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.Pipe() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。