Skip to content
Snippets·Free

Rust snippets

20 Rust snippets that only use the standard library, except one serde struct: error enums with From, iterator chains, counting with HashMap, let else, threads with Arc and Mutex, channels and a test module.

Free to install.

If PocketCode is installed on your Android device, this opens the page in the app.

Preview

5 of 20

Struct with a constructorstructnew

Struct with derives and a new function

#[derive(Debug, Clone)]
pub struct ${1:Config} {
    ${2:name}: ${3:String},
}

impl ${1:Config} {
    pub fn new(${2:name}: ${3:String}) -> Self {
        Self { ${2:name} }
    }
}

Enum with a methodenummatch

Enum plus an impl that matches on every variant

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ${1:Direction} {
    ${2:Up},
    ${3:Down},
}

impl ${1:Direction} {
    fn ${4:opposite}(self) -> Self {
        match self {
            Self::${2:Up} => Self::${3:Down},
            Self::${3:Down} => Self::${2:Up},
        }
    }
}

Custom error typeerrenum

Error enum with Display, Error and From so ? converts io errors

#[derive(Debug)]
pub enum ${1:AppError} {
    Io(std::io::Error),
    ${2:NotFound}(String),
}

impl std::fmt::Display for ${1:AppError} {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "I/O error: {e}"),
            Self::${2:NotFound}(what) => write!(f, "not found: {what}"),
        }
    }
}

impl std::error::Error for ${1:AppError} {}

impl From<std::io::Error> for ${1:AppError} {
    fn from(e: std::io::Error) -> Self {
        Self::Io(e)
    }
}

main that returns Resultmainres

Use ? in main and print the error if something fails

fn main() -> Result<(), Box<dyn std::error::Error>> {
    $0
    Ok(())
}

if let Someiflet

Run a block only when an Option has a value

if let Some(${1:value}) = ${2:option} {
    $0
}

Changes in 1.0.0

First version.

Related