Golang io.Copy()函数的使用示例

Golang io.Copy()函数的使用示例

在Go语言中,io包提供了基本的I/O原语接口,其主要工作是封装这些原语的实现方式。在Go语言中,使用 Copy() 函数,从指定的源(src)复制到目标(dst),直到src达到EOF即文件结尾或抛出错误为止。当src由WriterTo接口实现时,copy调用src.WriteTo(dst)来实现;否则,如果dst由ReaderFrom接口实现,则copy调用dst.ReadFrom(src)来实现。此外,该函数在io包中定义,您需要导入“io”包才能使用这些函数。

语法:

func Copy(dst Writer, src Reader) (written int64, err error)

在此处,“dst”是目标,“src”是源,从源中复制的内容将被复制到目标中。
返回值: 它返回int64类型的总字节数,这些字节被复制到“dst”,并返回从src到dst拷贝期间遇到的第一个错误,如果有的话。如果拷贝过程中没有错误,则返回“nil”。

以下示例说明了上述方法的用法:

示例1:

// Golang program to illustrate the usage of
// io.Copy() 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 Copy method with its parameters
    bytes, err := io.Copy(dst, src)
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    fmt.Printf("The number of bytes are: %d\n", bytes)
} 

输出:

GeeksforGeeks
The number of bytes are: 14

示例2:

// Golang program to illustrate the usage of
// io.Copy() 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("Nidhi: F\nRahul: M\nNisha: F\n")
  
    // Defining destination using Stdout
    dst := os.Stdout
  
    // Calling Copy method with its parameters
    bytes, err := io.Copy(dst, src)
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    fmt.Printf("The number of bytes are: %d\n", bytes)
} 

输出:

Nidhi: F
Rahul: M
Nisha: F
The number of bytes are: 27

在上面的示例中,使用了strings的NewReader()方法,从中读取要复制的内容。这里使用“Stdout”,以创建一个默认的文件描述符,在其中编写复制的内容。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程