在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的TeeReader()函數用於返回“Reader”,該“Reader”從聲明的“r”讀取,然後將其寫入聲明的“w”。然後,將通過聲明的“r”執行的所有讀取與對聲明的“w”的等效寫入進行比較。此方法不需要任何內部緩衝,並且讀取完成後即可完成寫入。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func TeeReader(r Reader, w Writer) Reader
在此,“r”是指定的讀取器,而“w”是指定的寫入器。
返回值:它返回一個“Reader”,該“Reader”從聲明的“r”讀取,然後將其寫入給定的“w”。但是,寫入內容時遇到的任何錯誤都將作為讀取錯誤返回。
以下示例說明了上述方法的使用:
範例1:
// Golang program to illustrate the usage of
// io.TeeReader() function
// Including main package
package main
// Importing fmt, io, strings, bytes, and os
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
// Calling main
func main() {
// Defining reader using NewReader method
reader:= strings.NewReader("GfG\n")
// Defining buffer
var buf bytes.Buffer
// Calling TeeReader method with its parameters
r:= io.TeeReader(reader, &buf)
// Calling Copy method with its parameters
Reader, err:= io.Copy(os.Stdout, r)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("n:%v\n", Reader)
}
輸出:
GfG n:4
在上麵的示例中,使用Copy()方法返回“Reader”,從此處寫入要讀取的內容的位置使用了NewReader()字符串方法,並且在此還使用了外部緩衝區。
範例2:
// Golang program to illustrate the usage of
// io.TeeReader() function
// Including main package
package main
// Importing fmt, io, strings, bytes, and os
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
// Calling main
func main() {
// Defining reader using NewReader method
reader:= strings.NewReader("GeeksforGeeks\nis\na\nCS-Portal.\n")
// Defining buffer
var buf bytes.Buffer
// Calling TeeReader method with its parameters
r:= io.TeeReader(reader, &buf)
// Calling Copy method with its parameters
Reader, err:= io.Copy(os.Stdout, r)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("n:%v\n", Reader)
}
輸出:
GeeksforGeeks is a CS-Portal. n:30
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 io.TeeReader() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。