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?
>Solution :
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 < len(data); i++ {
data[i] = i
}
}