Golang io.CopyN()函数的使用方法及示例
Go语言中,io包提供了I/O原语的基本接口,其主要工作是封装这些原语的实现。在Golang中, CopyN() 函数用于将“n”个字节从源复制到目标。如果目标由ReaderFrom接口实现,则使用它来进行复制。此外,该函数在io包中定义。在使用这些函数之前,您需要导入“io”包。
语法:
func CopyN(dst Writer, src Reader, n int64) (written int64, err error)
这里,“dst”是目标, “src”是从中复制内容到目标的源, “n”是需要从源中复制的字节数上限。
返回值: 它返回已经复制到目标“dst”的类型为int64的字节数,并返回在从src到dst复制过程中首次遇到的错误(如果有)。此外,只有当错误为“nil”时返回的字节数才是“n”。
以下示例说明了上述方法的使用:
示例 1:
// Golang program to illustrate the usage of
// io.CopyN() 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("GeeksforGeeks\n")
// Defining destination using Stdout
dst := os.Stdout
// Calling CopyN method with its parameters
bytes, err := io.CopyN(dst, src, 5)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("\nThe number of bytes are: %d\n", bytes)
}
输出:
Geeks
The number of bytes are: 5
在此示例中,“n”等于返回的字节数,因为错误为“nil”。
示例 2:
// Golang program to illustrate the usage of
// io.CopyN() 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("CS-Portal\n")
// Defining destination using Stdout
dst := os.Stdout
// Calling CopyN method with its parameters
bytes, err := io.CopyN(dst, src, 20)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("The number of bytes are: %d\n", bytes)
}
输出:
CS-Portal
panic: EOF
goroutine 1 [running]:
main.main()
/tmp/sandbox691649995/prog.go:29 +0x137
在上面的示例中,使用strings的NewReader()方法读取要复制的内容。 在这里,使用“Stdout”来创建默认文件描述符,在其中写入复制的内容。 此外,在这里返回的字节数小于“n”,因此会抛出EOF错误。
极客教程