在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的CopyBuffer()函數與Copy()方法相同,但唯一的例外是,如果需要一個而不是分配一個臨時緩衝區,它將通過提供的緩衝區顯示。如果src由WriterTo實現或dst由ReaderFrom實現,則將不使用緩衝區執行複製操作。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
在這裏,“dst”是目標,“src”是將內容複製到目標的源,而“buf”是在內存中保留永久空間的緩衝區。
返回值:它返回複製到“dst”的int64類型的字節總數,並且還返回從src複製到dst(如果有)時遇到的第一個錯誤。但是,如果緩衝區為零,則分配一個,否則,如果緩衝區的長度為零,則CopyBuffer會出現混亂。
以下示例說明了上述方法的用法:
範例1:
// Golang program to illustrate the usage of
// io.CopyBuffer() function
// Including main package
package main
// Importing fmt, io, os, and strings
import (
"fmt"
"io"
"os"
"strings"
)
// Calling main
func main() {
// Defining source
src:= strings.NewReader("GfG\n")
// Defining destination using Stdout
dst:= os.Stdout
// Defining buffer of length one using
// make keyword
buffer:= make([]byte, 1)
// Calling CopyBuffer method with its parameters
bytes, err:= io.CopyBuffer(dst, src, buffer)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("The number of bytes are:%d\n", bytes)
}
輸出:
GfG The number of bytes are:4
範例2:
// Golang program to illustrate the usage of
// io.CopyBuffer() function
// Including main package
package main
// Importing fmt, io, os, and strings
import (
"fmt"
"io"
"os"
"strings"
)
// Calling main
func main() {
// Defining two sources
src1:= strings.NewReader("GfG\n")
src2:= strings.NewReader("GeeksforGeeks is a CS-Portal\n")
// Defining destination using Stdout
dst:= os.Stdout
// Defining buffer of length one using
// make keyword
buffer:= make([]byte, 1)
// Calling CopyBuffer method with its parameters
bytes1, err:= io.CopyBuffer(dst, src1, buffer)
bytes2, err:= io.CopyBuffer(dst, src2, buffer)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("The number of bytes are:%d\n", bytes1)
fmt.Printf("The number of bytes are:%d\n", bytes2)
}
輸出:
GfG GeeksforGeeks is a CS-Portal The number of bytes are:4 The number of bytes are:29
在此,在上麵的示例中,使用了NewReader()字符串方法,從該方法中讀取要複製的內容。此處使用“Stdout”來創建默認文件描述符,並在其中寫入複製的內容。而且,上麵的相同緩衝區在調用CopyBuffer()方法時被重用,並且不需要額外的緩衝區來分配。
相關用法
- 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.CopyBuffer() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。