代码片段·免费
Rust 代码片段
20 个 Rust 代码片段,除一个 serde 结构体外只用标准库:带 From 的错误枚举、迭代器链、用 HashMap 计数、let else、配合 Arc 和 Mutex 的线程、通道以及测试模块。
免费安装。
如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。
预览
20 个中的 5 个
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
}1.0.0 的变更
首个版本。