Rust (5)


Turbofish in rust

Consider the following code (or run it in rust playground here):

If you ran it in the playground linked above, you will see the following compiler error.

Because collect() is so general, it can cause problems with type inference. As such, collect() is one of the few times you’ll see the syntax affectionately […]




Rust File Builder pattern for file read writes

  • March 20, 2021
  • Rust

Consider the following test code that creates a file, writes to it and then reads back to confirm what it wrote.

This test fails with a very cryptic and unhelpful message:

It will panic at this line file.read_to_string(&mut contents).unwrap(); What is happening is that File::create and File::open in rust are actually syntactic sugar […]




Temporary files and Temporary directory in Rust

  • March 20, 2021
  • Rust

I was looking for Python style temporary files and temporary directories in Rust. Very handy when writing tests for simulating actual files, or when we need to use files once or cache large amount of data for short time. We then let the operating system delete the files at a later time automatically or by […]




self in use statement in rust

  • March 18, 2021
  • Rust

I was going through some library code in a rust crate and this pattern had my head scratching: std::io::{self,Cursor}; What this is equivalent to is: use std::io; use std::io::Cursor; which means explicitly use std::io::Cursor and also use std::io itself. Thus, Cursor need not be prefixed but you’d still need to do io::BufReader and so on.




Rust tips: Box, RC, Arc, Cell, RefCell, Mutex

  • February 28, 2021
  • Rust

Difference Between Box, Rc, Arc, Cell (and its various variants.. RefCell, Mutex, RwLock) in Rust: Box is for single ownership. A great use case is to use this when we want to store primitive types (stored on stack) on heap. Rc is for multiple ownership. Arc is for multiple ownership, but threadsafe. RefCell is for […]