Skip to content

Instantly share code, notes, and snippets.

@stevedoyle
Last active October 20, 2022 09:01
Show Gist options
  • Save stevedoyle/1a47c24ac3d89c280ce9fbd6461919d8 to your computer and use it in GitHub Desktop.
Save stevedoyle/1a47c24ac3d89c280ce9fbd6461919d8 to your computer and use it in GitHub Desktop.
Rust code snippets

Rust Snippets

Pass a Vec<> by reference to a function

let data: vec![0u8; 1024];
foo(data.as_ref()); // Passes an immutable slice

fn foo(data: &[u8]) {
    ...
}

let mut data: vec![0u8; 1024];
bar(data.as_mut_slice()); 

//! Takes an mutable slice. The contents can be changed but its size cannot.
fn bar(data: &mut [u8]) {
    ...
}

foobar(data);

//! Vector contents and size can be changed.
fn foobar(data: &mut Vec<u8>) {
    ...
}

Create a zero filled array / vector

let x = [0u8; 10]; // 10 element array filled with zeros
let x = vec![0i32; 10]; // 10 element array of i32s filled with zeros
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment