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


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

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的CopyN()函數用於將“n”字節從源複製到目標。如果dst由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

在此,在串的上述例子NewReader()方法是從其中讀出要複製的內容使用。而“Stdout”用在這裏為了創造一個複製的內容寫了一個默認的文件描述符。此外,此處返回的字節數少於“n”,因此上麵拋出了EOF錯誤。




相關用法


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