go – How to get byte slice of large file?-ThrowExceptions

Exception or error:

I have a large file stored at path and want to efficiently cut out a byte slice text from index x to index y. This is my code so far:

content, err := ioutil.ReadFile(path)
text = content[x:y]
// do something with text

The problem with my current implementation is that I run into memory issues with large files.

fatal error: runtime: out of memory

How can I avoid this?

How to solve:

With the help of yazgazan I was able to come up with a solution by using File.ReadAt:

f, err := os.Open(path)
text := make([]byte, y-x)
_, err = f.ReadAt(text, int64(x))

Leave a Reply

Your email address will not be published. Required fields are marked *