Snippets·Grátis
Snippets de Rust
20 snippets de Rust que usam só a biblioteca padrão, exceto um struct com serde: enums de erro com From, cadeias de iteradores, contagem com HashMap, let else, threads com Arc e Mutex, canais e um módulo de testes.
Instalação grátis.
Se o PocketCode estiver instalado no seu Android, isto abre a página no app.
Prévia
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
}Mudanças na 1.0.0
Primeira versão.