Snippets·Gratis
Snippets de Rust
20 snippets de Rust que solo usan la biblioteca estándar, salvo un struct con serde: enums de error con From, cadenas de iteradores, contar con HashMap, let else, hilos con Arc y Mutex, canales y un módulo de tests.
Se instala gratis.
Si tienes PocketCode instalado en tu Android, esto abre la página en la app.
Vista previa
5 de 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
}Cambios en la 1.0.0
Primera versión.