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


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

在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的PipeReader.Close()函數用於關閉閱讀器。但是,連續寫入PipeWriter,即,寫入一半的管道將返回ErrClosedPipe錯誤。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。

用法:

func (r *PipeReader) Close() error

此處,“r”是指向PipeReader的指針。其中PipeReader是管道的讀取一半。

返回值:它返回調用Close方法之前編寫的內容。然後連續寫入PipeWriter,即,寫入一半的管道將返回ErrClosedPipe錯誤。

範例1:



// Golang program to illustrate the usage of 
// io.pipeReader.Close() function 
  
// Including main package 
package main 
  
// Importing fmt and io 
import ( 
    "fmt"
    "io"
) 
  
// Calling main 
func main() { 
  
    // Calling Pipe method 
    pipeReader, pipeWriter:= io.Pipe() 
  
    // Calling Write method in go function 
    go func() { 
        pipeWriter.Write([]byte("GfG")) 
        pipeWriter.Write([]byte("GeeksforGeeks")) 
        pipeWriter.Write([]byte("GfG is a CS-Portal.")) 
    }() 
  
    // Creating buffer using make keyword 
    // of specified length 
    buffer:= make([]byte, 50) 
  
    // Using for loop 
    for i:= 0; i < 2; i++ { 
  
        // Reading the contents in buffer 
        n, err:= pipeReader.Read(buffer) 
  
        // If error is not nil panic 
        if err != nil { 
            panic(err) 
        } 
  
        // Calling Close method 
        pipeReader.Close() 
  
        // Prints the content read in buffer 
        fmt.Printf("%s\n", buffer[:n]) 
    } 
}

輸出:

GfG
panic:io:read/write on closed pipe

goroutine 1 [running]:
main.main()
    /tmp/sandbox180013044/prog.go:38 +0x302

在這裏,隻有一個Write操作的內容按其在Close()方法之前的寫入方式返回,但不返回在Close方法之後寫入的內容,而是引發ErrClosedPipe錯誤。

範例2:

// Golang program to illustrate the usage of 
// io.pipeReader.Close() function 
  
// Including main package 
package main 
  
// Importing fmt and io 
import ( 
    "fmt"
    "io"
) 
  
// Calling main 
func main() { 
  
    // Calling Pipe method 
    pipeReader, pipeWriter:= io.Pipe() 
  
    // Calling Write method in go function 
    go func() { 
        pipeWriter.Write([]byte("GfG")) 
        pipeWriter.Write([]byte("GeeksforGeeks")) 
        pipeWriter.Write([]byte("GfG is a CS-Portal.")) 
    }() 
  
    // Creating buffer using make keyword 
    // of specified length 
    buffer:= make([]byte, 50) 
  
    // Calling Close method 
    pipeReader.Close() 
  
    // Using for loop 
    for i:= 0; i < 2; i++ { 
  
        // Reading the contents in buffer 
        n, err:= pipeReader.Read(buffer) 
  
        // If error is not nil panic 
        if err != nil { 
            panic(err) 
        } 
  
        // Prints the content read in buffer 
        fmt.Printf("%s\n", buffer[:n]) 
    } 
}

輸出:

panic:io:read/write on closed pipe

goroutine 1 [running]:
main.main()
    /tmp/sandbox881512815/prog.go:41 +0x2ea

在此,由於在進行任何讀取操作之前調用了Close()方法,因此不會將任何內容讀入緩衝區,因此不會讀取任何內容,並且隻會在此處引發錯誤。




相關用法


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