I'm still really new to rust
, but it's been fascinating so far. Forgive me if some of my syntax is off. I'm still getting used to statically/strongly-typed languages again.
I noticed that read_to_string()
can either be used as a module-level function, or as a method of sorts (still learning/remembering rust
's terminology) that's attached to the File
handle object. Are these two different functions though? They seem to be, but I can't find docs that define both of them.
The module-level version appears to take a single string param for the file name, and return a Result<T, E>
like so:
let contents = fs::read_to_string("readme.txt").expect("Invalid file");
fs::read_to_string()
is pretty straightforward: provide a file/path, and it'll string that contains the contents of the file wrapped in a Result
if all goes well.
The read_to_string()
method that is attached to a File
object seems less straightforward:
let f = File::open("readme.txt").expect("Invalid file");
let mut contents = String::new();
match f.read_to_string(&mut contents) {
Ok(_) => println!("loaded file: {}", contents),
Err(e) => println!("error occurred: {}", e);
};
Since this is a File
handle object, it can be assumed that the file is already opened, and so it appears to take a mutable string to serve a memory location of where to allocate and fill the contents with the file's data. Still makes sense. It also appears to return a Result<T, E>
in case of errors, which makes sense for errors, but not for succeses. What does the Ok()
variant return? Is it just a unit()? How come read_to_string()
takes a mutable reference in this case? Couldn't that method instantiate a new string within its implementation details, and return the newly-allocated string in its Ok()
variant instead like fs::read_to_string()
does?
My only guess is that this somehow violates the borrow checker because this function is a method that's attached to an object, and this goes the memory/scoping rules that the borrow checker is supposed to enforce. Does that sound about right?
I've gone through the borrow checker stuff a lot, but I'm still wrapping my head around it.