下面是示例代码:人员的定义type Person struct { Data string done bool}实现写入func (person *Person) Write(p []byte) (int,error) { person.Data = string(p) return len(p), nil}实现读取func (person *Person) Read(p []byte) (int,error) { if person.done { return 0, io.EOF } for index, b := range []byte(person.Data) { p[index] = b } // len(p) = 512 <- length p []byte person.done = true return len(person.Data), nil}写入一些数据func writeTo(out io.Writer) error { if _, err := out.Write([]byte("test")); err != nil { return err } fmt.Println("Write done") return nil}主要func main() { p := &Person{} writeTo(p) s, err := ioutil.ReadAll(p) if err != nil { panic(err) } fmt.Println("result:",string(s),len(s))}如所注意到的,p []字节长度为512。我想知道为什么它变成512长度。
1 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
您的代码调用 :ReadAll
s, err := ioutil.ReadAll(p)
ReadAll基本上像这样工作:
package main
import "fmt"
func main() {
// first, make an empty slice, with a reserve space of 512
b := make([]byte, 0, 512)
// then, write data into the reserve space
n := copy(b[:cap(b)], "north")
// then, increase the slice to how much data was just written
b = b[:n]
// 5 [110 111 114 116 104]
fmt.Println(n, b)
}
https://github.com/golang/go/blob/go1.16.3/src/io/io.go#L626
- 1 回答
- 0 关注
- 71 浏览
添加回答
举报
0/150
提交
取消