Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading