io.Readerio.Readerio.Reader
字节切片到 io.Reader
io.Reader
package main
import (
"bytes"
"log"
)
func main() {
data := []byte("this is some data stored as a byte slice in Go Lang!")
// convert byte slice to io.Reader
reader := bytes.NewReader(data)
// read only 4 byte from our io.Reader
buf := make([]byte, 4)
n, err := reader.Read(buf)
if err != nil {
log.Fatal(err)
}
log.Println(string(buf[:n]))
}
预期输出如下
2023/01/03 07:53:52 this
https://play.golang.org/p/pzTj9J8aJyL
io.Reader 到字节片
io.Reader
package main
import (
"bytes"
"log"
"strings"
)
func main() {
ioReaderData := strings.NewReader("this is some data stored as a byte slice in Go Lang!")
// creates a bytes.Buffer and read from io.Reader
buf := &bytes.Buffer{}
buf.ReadFrom(ioReaderData)
// retrieve a byte slice from bytes.Buffer
data := buf.Bytes()
// only read the first 4 bytes
log.Println(string(data[:4]))
}
预期输出如下
2023/01/03 07:55:15 this
https://play.golang.org/p/TPVm7Y7XIus
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。