name: rust-development description: Guts项目的Rust开发最佳实践 - 惯用代码、错误处理、异步模式和commonware集成
Guts项目的Rust开发技能
您正在使用commonware原语开发一个用于去中心化基础设施的Rust项目。
代码风格指南
通用原则
- 惯用Rust:遵循Rust的惯用写法和约定
- 内存安全:利用借用检查器,除非绝对必要,否则避免使用unsafe
- 错误处理:库错误使用
thiserror,应用程序使用anyhow - 文档:每个公共项都需要包含示例的文档
格式化与代码检查
# 提交前始终运行
cargo fmt --all
cargo clippy --all-targets --all-features -- -D warnings
错误处理模式
use thiserror::Error;
#[derive(Debug, Error)]
pub enum RepositoryError {
#[error("未找到仓库: {0}")]
NotFound(String),
#[error("仓库权限被拒绝: {0}")]
PermissionDenied(String),
#[error("存储错误: {0}")]
Storage(#[from] StorageError),
}
pub type Result<T> = std::result::Result<T, RepositoryError>;
异步模式
使用Tokio作为异步运行时,采用结构化并发:
use tokio::sync::{mpsc, oneshot};
// 优先使用通道而非共享状态
pub struct Service {
tx: mpsc::Sender<Command>,
}
impl Service {
pub async fn query(&self, request: Request) -> Result<Response> {
let (tx, rx) = oneshot::channel();
self.tx.send(Command::Query { request, reply: tx }).await?;
rx.await?
}
}
模块结构
// lib.rs - 重新导出公共API
pub mod error;
pub mod types;
pub mod service;
pub use error::{Error, Result};
pub use types::*;
pub use service::Service;
测试
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_feature() {
// 准备
let service = Service::new().await;
// 执行
let result = service.do_something().await;
// 断言
assert!(result.is_ok());
}
}
Commonware集成
关键依赖包
commonware-cryptography:用于Ed25519签名commonware-p2p:用于点对点网络commonware-consensus:用于BFT共识commonware-storage:用于持久化存储commonware-codec:用于序列化
示例:使用加密功能
use commonware_cryptography::{Ed25519, Signer, Verifier};
pub struct Identity {
keypair: Ed25519,
}
impl Identity {
pub fn new() -> Self {
Self {
keypair: Ed25519::generate(),
}
}
pub fn sign(&self, message: &[u8]) -> Signature {
self.keypair.sign(message)
}
}
Cargo.toml最佳实践
[package]
name = "guts-core"
version = "0.1.0"
edition = "2021"
rust-version = "1.75"
license = "MIT OR Apache-2.0"
description = "Guts的核心类型和特征"
repository = "https://github.com/AbdelStark/guts"
keywords = ["decentralized", "git", "p2p"]
categories = ["development-tools"]
[dependencies]
# 使用工作区依赖
thiserror = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
tokio-test = { workspace = true }
[lints.rust]
unsafe_code = "deny"
missing_docs = "warn"
[lints.clippy]
all = "warn"
pedantic = "warn"
nursery = "warn"
性能考虑
- 在异步任务间共享所有权时使用
Arc - 零拷贝网络传输优先使用
bytes::Bytes - 并发哈希映射使用
dashmap - 优化前使用
flamegraph进行性能分析