在Go語言中,io軟件包為I /O原語提供基本接口。它的主要工作是封裝此類原始之王的正在進行的實現。 Go語言中的SectionReader.Read()函數用於返回NewSectionReader方法讀取的字節數。此方法將緩衝區作為其參數。而且,此函數在io包下定義。在這裏,您需要導入“io”包才能使用這些函數。
用法:
func (s *SectionReader) Read(p []byte) (n int, err error)
在這裏,“s”是指向由NewSectionReader方法返回的SectionReader的指針,而“p”是指定字節長度的緩衝區。
返回值:它返回從指定長度的指定緩衝區返回的內容的字節數,並且還返回錯誤(如果沒有錯誤),然後返回“nil”。
以下示例說明了上述方法的使用:
範例1:
// Golang program to illustrate the usage of
// io.SectionReader.Read() function
// Including main package
package main
// Importing fmt, io, and strings
import (
"fmt"
"io"
"strings"
)
// Calling main
func main() {
// Defining reader using NewReader method
reader:= strings.NewReader("Geeks\n")
// Calling NewSectionReader method with its parameters
r:= io.NewSectionReader(reader, 2, 4)
// Defining buffer using make keyword
buf:= make([]byte, 3)
// Calling Read method with its parameter
n, err:= r.Read(buf)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("Content in buffer:%s\n", buf)
fmt.Printf("n:%v\n", n)
}
輸出:
Content in buffer:eks n:3
在上麵的示例中,緩衝區的內容隻有三個字節,因此,返回“3”,並且在讀取陳述的內容時沒有拋出錯誤,因此錯誤為“nil”。
範例2:
// Golang program to illustrate the usage of
// io.SectionReader.Read() function
// Including main package
package main
// Importing fmt, io, and strings
import (
"fmt"
"io"
"strings"
)
// Calling main
func main() {
// Defining reader using NewReader method
reader:= strings.NewReader("GeeksforGeeks\nis\na\nCS-Portal.")
// Calling NewSectionReader method with its parameters
r:= io.NewSectionReader(reader, 6, 34)
// Defining buffer using make keyword
buf:= make([]byte, 25)
// Calling Read method with its parameter
n, err:= r.Read(buf)
// If error is not nil then panics
if err != nil {
panic(err)
}
// Prints output
fmt.Printf("Content in buffer:%s\n", buf)
fmt.Printf("n:%v\n", n)
}
輸出:
panic:EOF goroutine 1 [running]: main.main() /tmp/sandbox125171693/prog.go:31 +0x25a
此處,以上代碼中使用的緩衝區中的內容的字節數少於說明的字節數,因此會引發EOF錯誤。
相關用法
- 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.SectionReader.Read() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。