os.File的Read方法如何修改golang中切片的字节?

huangapple go评论83阅读模式
英文:

How os.File Read method modifies the bytes of slice in golang?

问题

例如,在下面的示例中,Datamain 块中不会改变 -

import "fmt"

func main(){
    Data := make([]byte,3)
    Modify(Data)
    fmt.Println(Data) //输出为 [0,0,0]
}

func Modify(data []byte){
    data = []byte{1,2,3}
}

但是,在读取文件并将字节存储到切片 b 中时,读取方法可以更改 b 中的字节 -
如此写在这里

func (f *File) Read(b []byte) (n int, err error)

Read 方法如何修改调用者的 b

英文:

For example in below, Data is not going to change in main block -

import "fmt"

func main(){
    Data := make([]byte,3)
    Modify(Data)
    fmt.Println(Data) //output is [0,0,0]
}

func Modify(data []byte){
	data = []byte{1,2,3}
}

But while reading a file and storing bytes to a slice b, the read method can change the bytes in b -
As Written Here

func (f *File) Read(b []byte) (n int, err error)

How does Read Method can modify caller's b?

答案1

得分: 1

Read可以修改b,因为你传递了一个非零长度的切片。Read将字节设置到b中,直到指定的长度... 它不会设置b的切片。你自己的函数Modify设置的是一个局部副本的切片。如果你按索引分配到切片的长度,Modify也会有修改行为。

func Modify(data []byte) {
    for i := 0; i < len(data); i++ {
        data[i] = i
    }
}
英文:

Read can modify b because you pass a slice with nonzero length. Read sets the bytes into b up to length... it does not set b slice. Your own function Modify sets the slice that is a local copy. If you assign by index up to slice length, Modify also has modifying behaviour.

func Modify(data []byte) {
    for i := 0; i &lt; len(data); i++ {
        data[i] = i
    }
}

huangapple
  • 本文由 发表于 2022年5月20日 21:10:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/72319482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定