當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang io.Copy()用法及代碼示例

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的Copy()函數用於從指定的src(即源)複製到dst(即目標),直到在src上達到EOF(即文件結尾)或引發錯誤為止。在此,當WriterTo接口實現src時,則通過調用src.WriteTo(dst)來實現副本。否則,如果dst由ReaderFrom接口實現,則通過調用dst.ReadFrom(src)來實現副本。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

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

在此,“dst”是目標,“src”是將內容複製到目標的源。
返回值:它返回複製到“dst”的int64類型的字節總數,並且還返回從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

在此,在上麵的示例中,使用了NewReader()字符串方法,從該方法中讀取要複製的內容。此處使用“Stdout”來創建默認文件描述符,並在其中寫入複製的內容。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.Copy() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。