Code snippets wih useful stuff about Rust

Read/write files 1

use std::fs;

fn main() {
    let data: String = fs::read_to_string("file-to-read.txt").expect("Unable to read file");
    println!("{}", data);
}

Read a file as a Vec<u8>

use std::fs;
fn main() {
    let data: Vec<u8> = fs::read("file-to-read.txt").expect("Unable to read file");
    println!("{}", data);
}

Write to a file

use std::fs;

fn main() {
    let data: String = "Some data!";
    fs::write("/tmp/file-to-write.txt").expect("Unable to write a file");    
}

Insert or replace multiple items in a Vec 2

let mut vec = vec![1, 5];
let slice = &[2, 3, 4];

let index = 1;

vec.splice(index..index, slice.iter().cloned());

println!("{:?}", vec); // [1, 2, 3, 4, 5]

  1. What is the de-facto way of reading and writing files in Rust. ↩︎

  2. Efficiently insert or replace multiple elements in the middle or at the beginning of a Vec. ↩︎