Rust错误处理模式:从Result到自定义错误类型

Rust:专业级错误处理工具 thiserror 详解 Rust错误处理库thiserror详解:专为库开发设计,支持自定义错误类型和自动特征实现。通过#[derive(Error)]宏可快速定义包含格式化错误信息、错误来源和回溯的枚举或结构体错误类型。相比anyhow更适合需要精确错误控制的场景,支持模式匹配和高效错误处理。文章涵盖安装、核心功能、属性详解、最佳实践及与anyhow的对比,是库开发者提升错误处理能力的实用指南。 阅读详情

Rust错误处理模式:从Result到自定义错误类型

引言

错误处理是编写健壮代码的关键。Rust提供了强大的错误处理机制,通过Result和Option类型在编译时强制处理错误。

本文将深入探讨Rust中的错误处理模式,包括标准错误类型、自定义错误、错误转换和最佳实践。

一、基本错误处理

1.1 Result类型

use std::fs::File;
use std::io::Read;

fn read_file_contents(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn main() {
    match read_file_contents("example.txt") {
        Ok(contents) => println!("File contents: {}", contents),
        Err(e) => eprintln!("Error reading file: {}", e),
    }
}

1.2 Option类型

fn find_user(id: u32) -> Option<String> {
    let users = vec![(1, "Alice"), (2, "Bob"), (3, "Charlie")];
    
    users.into_iter()
        .find(|(user_id, _)| *user_id == id)
        .map(|(_, name)| name.to_string())
}

fn main() {
    match find_user(2) {
        Some(name) => println!("Found user: {}", name),
        None => println!("User not found"),
    }
    
    let name = find_user(5).unwrap_or_else(|| "Unknown".to_string());
    println!("User: {}", name);
}

二、自定义错误类型

2.1 使用enum定义错误类型

use std::fmt;

#[derive(Debug)]
enum AppError {
    IoError(std::io::Error),
    ParseError(String),
    ValidationError { field: String, message: String },
    NotFound,
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::IoError(e) => write!(f, "IO error: {}", e),
            AppError::ParseError(s) => write!(f, "Parse error: {}", s),
            AppError::ValidationError { field, message } => {
                write!(f, "Validation error in {}: {}", field, message)
            }
            AppError::NotFound => write!(f, "Resource not found"),
        }
    }
}

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

2.2 使用thiserror简化错误定义

use thiserror::Error;

#[derive(Error, Debug)]
enum DatabaseError {
    #[error("Connection failed: {0}")]
    ConnectionError(#[from] std::io::Error),
    
    #[error("Query execution failed: {0}")]
    QueryError(String),
    
    #[error("Record not found with id: {0}")]
    RecordNotFound(u64),
    
    #[error("Invalid query: {0}")]
    InvalidQuery {
        query: String,
        reason: String,
    },
}

fn execute_query(query: &str) -> Result<(), DatabaseError> {
    if query.is_empty() {
        return Err(DatabaseError::InvalidQuery {
            query: query.to_string(),
            reason: "Query cannot be empty".to_string(),
        });
    }
    Ok(())
}

三、错误转换

3.1 使用From trait

use std::io;
use std::num::ParseIntError;

enum ConversionError {
    IoError(io::Error),
    ParseError(ParseIntError),
}

impl From<io::Error> for ConversionError {
    fn from(e: io::Error) -> Self {
        ConversionError::IoError(e)
    }
}

impl From<ParseIntError> for ConversionError {
    fn from(e: ParseIntError) -> Self {
        ConversionError::ParseError(e)
    }
}

fn read_and_parse(path: &str) -> Result<i32, ConversionError> {
    let mut contents = String::new();
    std::fs::File::open(path)?.read_to_string(&mut contents)?;
    let value = contents.trim().parse()?;
    Ok(value)
}

3.2 使用?操作符

fn process_data() -> Result<String, Box<dyn std::error::Error>> {
    let data = read_file_contents("data.txt")?;
    let parsed = parse_data(&data)?;
    Ok(format!("Processed: {}", parsed))
}

fn read_file_contents(path: &str) -> Result<String, std::io::Error> {
    std::fs::read_to_string(path)
}

fn parse_data(data: &str) -> Result<i32, std::num::ParseIntError> {
    data.parse()
}

四、错误处理模式

4.1 early return模式

fn validate_user(user: &User) -> Result<(), ValidationError> {
    if user.name.is_empty() {
        return Err(ValidationError::EmptyName);
    }
    
    if user.email.is_empty() {
        return Err(ValidationError::EmptyEmail);
    }
    
    if !user.email.contains('@') {
        return Err(ValidationError::InvalidEmail);
    }
    
    Ok(())
}

struct User {
    name: String,
    email: String,
}

#[derive(Debug)]
enum ValidationError {
    EmptyName,
    EmptyEmail,
    InvalidEmail,
}

4.2 错误恢复模式

fn get_config_value(key: &str) -> Result<String, ConfigError> {
    // 首先尝试从环境变量获取
    if let Ok(value) = std::env::var(key) {
        return Ok(value);
    }
    
    // 如果失败,尝试从配置文件获取
    let config = load_config()?;
    config.get(key)
        .cloned()
        .ok_or(ConfigError::KeyNotFound(key.to_string()))
}

enum ConfigError {
    IoError(std::io::Error),
    ParseError(serde_json::Error),
    KeyNotFound(String),
}

4.3 错误包装模式

use std::error::Error;

#[derive(Debug)]
struct WrappedError {
    source: Box<dyn Error + Send + Sync + 'static>,
    context: String,
}

impl WrappedError {
    fn new<E>(source: E, context: &str) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        WrappedError {
            source: Box::new(source),
            context: context.to_string(),
        }
    }
}

impl std::fmt::Display for WrappedError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}: {}", self.context, self.source)
    }
}

impl Error for WrappedError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&*self.source)
    }
}

五、错误处理最佳实践

5.1 使用anyhow进行简化

use anyhow::{Context, Result};

fn process_file(path: &str) -> Result<String> {
    let contents = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read file: {}", path))?;
    
    let data = parse_contents(&contents)
        .with_context(|| "Failed to parse contents")?;
    
    Ok(data)
}

fn parse_contents(contents: &str) -> Result<String> {
    if contents.is_empty() {
        anyhow::bail!("Contents cannot be empty");
    }
    Ok(contents.to_string())
}

5.2 使用eyre进行更优雅的错误处理

use eyre::{eyre, Result, WrapErr};

fn main() -> Result<()> {
    let config = load_config().wrap_err("Failed to load configuration")?;
    let connection = connect_to_database(&config)
        .wrap_err("Failed to connect to database")?;
    
    Ok(())
}

fn load_config() -> Result<Config> {
    Err(eyre!("Configuration file not found"))
}

struct Config;

fn connect_to_database(_config: &Config) -> Result<()> {
    Ok(())
}

5.3 错误日志记录

use log::{error, info};

fn process_request(request: Request) -> Result<Response, AppError> {
    info!("Processing request: {:?}", request);
    
    let result = do_processing(&request).map_err(|e| {
        error!("Processing failed: {}", e);
        e
    })?;
    
    Ok(result)
}

struct Request;
struct Response;

fn do_processing(_request: &Request) -> Result<Response, AppError> {
    Err(AppError::ProcessingError)
}

#[derive(Debug)]
enum AppError {
    ProcessingError,
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

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

六、总结

Rust错误处理的特点:

  1. 类型安全:编译时强制处理错误
  2. 明确的错误类型:Result和Option
  3. 灵活的错误转换:From trait和?操作符
  4. 丰富的生态系统:thiserror、anyhow、eyre等

在实际项目中,建议:

  • 使用thiserror定义自定义错误类型
  • 使用anyhow或eyre简化错误处理
  • 为错误添加上下文信息
  • 记录错误日志便于调试

思考:在你的Rust项目中,错误处理的最佳实践是什么?欢迎分享!

【Rust错误处理】Rust错误处理机制详解与应用实战 在 Rust 中,错误处理是一个核心特性,它通过 Result 和 Option 类型以及 panic! 机制来管理错误和异常情况。Rust 的错误处理强调显式性和安全性,避免了传统异常机制的隐式控制流问题。 Rust 主要有两种错误处理方式:可恢复错误和不可恢复错误。 阅读详情

相关推荐

11、Rust 中的错误处理与枚举类型使用

本文介绍了 Rust 中的两种错误处理方法:使用全局变量和使用 Result 返回类型,以及枚举类型的定义和应用。通过示例代码和流程图,详细讲解了不同方法的原理、实现步骤及优缺点,并对比了它们的适用场景。此外,还探讨了枚举类型的使用优势及其在状态管理中的作用,帮助开发者更好地进行 Rust 编程。

s3t4u的博客 58

Rust基础-错误处理-自定义错误之一

简单分析Rust错误返回机制。

DarcyZ_SSM的博客 4304

Rust错误处理笔记:从Result到自定义错误

在Rust中,Result是一个由枚举(enum)类型提供的类型,用于处理错误。它被定义为,其枚举体包含两个变体:Ok和Err。Ok变体用于表示操作成功,并可以携带任何类型的数据。相反,Err变体用于表示错误,并可以携带错误信息。Ok(T),Err(E),这里T表示成功值的类型,而E表示错误值的类型。这种泛型设计使得Result非常灵活,可以应用于不同类型的操作和错误处理。Rust的Option<T>类型是枚举的一种,用来编码一个值可能缺失的情况。

weixin_42437253的博客 1209

Rust错误处理

Rust错误处理

alex wang的博客 995

关于【中孚计算机终端保密检查系统】的卸载

卸载中孚计算机终端保密检查系统

码农之路,向死而生 4万+

如何理解反步法设计控制器?

假设以二阶系统为例,被控对象的系统状态方程为: 基于反步控制的具体方法如下: 1.1步骤一 定义期望状态为xd,状态误差e1,为: e1=x1-xd; 则e1的导数为: 1.2步骤二 定义虚拟控制量为: e2定义为: 1.3步骤三 定义Lyapunov能量函数为: 1.4步骤四 定义总Lyapunov能量函数为: 因此设计的控制律为: 设计c>0,则: 满足Lyapunov的稳定性判定条件...

weixin_42736130的博客 2万+

RUST:错误处理 thiserror 详解

thiserror的作用可以概括为一句话:用声明式写法生成标准 Rust 错误实现。生成实现;定义当前层的Display;#[from]生成直接错误转换,并隐含#[source];#[source]保留底层原因;在没有新错误语义时透明转发。真正决定代码质量的,仍然是错误类型本身:变体是否反映业务事实,上下文是否在正确层补充,source 是否完整,显示文本是否重复,公开 API 是否承担了明确而稳定的承诺。宏替开发者省下样板代码,省下来的注意力应该用在这些问题上。

gopher9511的博客 273

S7-1200PLC期末复习题(第七章)

A.0 B.1 C.4 D.-4 A、CV = 0 B、CV = 1 C、CV < 4 D、CV >= 4A、0,0 B、3,0 C、1,1 D、3,1 A、0 B、1 C、先是1,再变为0 D、先是0,再变为1置位输出:常开触点M0.0闭合,Q0.0变为1状态并保存该状态,即使M0.0断开,Q0.0也保持1状态。 复位输出:常开触点M0.1闭合时,Q0.0变为0状态并保持该状态,即使M0.1断开,Q0.0也保持为0状态。 A、1 B、0 C、5 D、10RESET_BF指令需要两个参数,第一个是复位的位数

qq_52251819的博客 4423

Rust 错误处理(二)

文章目录一、自定义返回错误信息二、完整的错误处理 Rust 错误处理示例: 一、自定义返回错误信息 声明自定义错误种类的枚举体,为错误枚举体实现Display ,为每种错误实现 From use std::io::{self,Read}; use std::fs::File; use std::path::Path; use std::fmt::{self,Debug}; use std::num; #[derive(Debug)] enum CliError{ Io(io::Error),

红叶谷 wsp_1138886114的博客 2144

MySQL表名大小写敏感问题终极解决:lower_case_table_names=1不生效的3个隐藏坑

本文深入剖析了MySQL表名大小写敏感问题中,设置lower_case_table_names=1参数不生效的三个核心原因。关键在于理解该参数只能在数据库初始化前设置,并需排查配置文件优先级与正确停止服务的顺序。文章提供了从Windows迁移到Linux的完整避坑指南与验证方法,帮助DBA和开发者彻底解决这一跨平台兼容性难题。

weixin_29229055的博客 395

逆向工程师的Shopee爬虫避坑指南:af-ac-enc-dat参数生成原理与反反爬策略

本文深入剖析了Shopee电商平台的反爬虫加密机制,重点解析了核心请求头参数x-sap-ri、x-sap-sec及af-ac-enc-dat的生成原理与联动关系。文章从逆向工程视角,提供了定位加密代码、分析算法逻辑的实战方法,并分享了基于JS执行环境模拟与无头浏览器控制的可持续反反爬策略,为高效、稳定地采集数据提供专业指南。

weixin_28607671的博客 1497

Rust-by-example-cn实战:5个经典Rust错误处理案例深度解析

Rust-by-example-cn是Rust语言学习的优质资源,其中错误处理章节详细介绍了Rust独特的错误处理机制。本文将通过5个经典案例,带你快速掌握Rust中Option和Result的核心用法,让你的代码更健壮、更优雅。 ## 案例一:使用`?`运算符简化错误传播 在Rust中,`?`运算符是处理错误的利器,它可以自动将错误传播出去,避免繁琐的match嵌套。当遇到Err时,`?`会

gitblog_00357的博客 656

NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.解决方案

本文主要介绍了NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.解决方案,希望能对使用jupyter notebook的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 11万+

Remacs错误处理:Rust Result类型如何彻底改进代码健壮性

在Emacs社区中,Remacs项目以其创新的Rust实现方式引起了广泛关注。作为将Emacs从C语言逐步迁移到Rust的开源项目,Remacs展示了现代编程语言如何从根本上改进传统软件的架构和可靠性。本文将深入探讨Remacs如何利用Rust的Result类型和错误处理机制,显著提升代码的健壮性和安全性。🚀 ## Rust错误处理的核心优势 Remacs项目充分利用了Rust语言的核心特性

gitblog_00341的博客 1100

3.嵌入式控制器EC学习,源码框架(60/64端口)(一)

服务函数剖析 上一篇讲到while循环会一直查询十六个标志位是否满足要求,一旦其中某个标志位为1时,程序将会执行相应的服务函数,而执行服务函数是通过函数指针(service_table[ _R1 ])();来实现的。接下来我们分别来看看这十六个服务函数分别包含了哪些内容。 16个函数的函数名如下: const FUNCT_PTR_V_V code service_table[16] = { // Hi-Level Service Service_PCI, // Host 6

qq_30135687的博客 4160

【OpenClaw】Edict 三省六部制部署与启动

文章摘要 本文聚焦Edict系统的本地部署与启动,提供三种安装方式:Docker快速体验、macOS/Linux原生安装和Windows生产仿真。核心目标是让用户能够独立完成系统启动和基础问题排查,确保看板、后端服务、同步脚本和网关正常运行。文章强调环境检查的重要性,并给出具体验收标准:浏览器能访问看板页面(http://127.0.0.1:7891)和接口返回JSON数据。同时提供一键启动/停止脚本和常见问题处理建议,帮助用户快速验证部署结果。配套系列教程涵盖部署启动、使用实战、二次开发和封装版本使用等内

Mr数据杨 2904

gtk4-rs最佳实践:性能优化、错误处理和代码组织的10个技巧

gtk4-rs是GTK 4的Rust绑定库,它让开发者能够使用Rust语言创建功能强大的桌面应用程序。本文将分享10个实用技巧,帮助你在使用gtk4-rs开发时提升性能、优化错误处理并改进代码组织,打造更高效、更可靠的应用。 ## 一、性能优化技巧 ### 1. 利用模型-视图-控制器(MVC)模式提升列表性能 在处理大量数据时,采用MVC模式可以显著提升性能。gtk4-rs提供了高效的列表模

gitblog_01103的博客 461

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Rust 错误处理完全指南:从 Result 到自定义错误类型

本文深入解析Rust的错误处理机制,重点介绍了Result和Option类型的用法,以及?运算符的工作原理。通过对比其他语言的异常处理方式,突出Rust显式错误处理的优势。文章详细讲解如何设计自定义错误类型(包括简单枚举、实现标准trait和使用thiserror/anyhow库),并提供了错误处理最佳实践和实战案例(HTTP客户端、数据验证器等)。最后讨论了panic的合理使用场景和自定义处理方式,总结Rust错误处理的核心优势:类型安全、零成本抽象和强制显式处理。

seven_1243096140的博客 1117

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

[Rust 入门] Rust 错误处理 - Panic 与 Result

自定义JsonError错误。// 错误应该能打印write!// 错误应该实现 std::error::Error 特型,但使用 Error 各个方法的默认定义就够了可以使用thiserrorcrate 来简化上面的操作。

编程回响 1571

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Rust错误类型设计:zero-to-production中的自定义错误与Result处理

你是否曾在Rust项目中遇到错误处理代码混乱、错误类型不明确、错误信息难以追踪的问题?在大型项目中,不良的错误处理设计会导致调试困难、API稳定性差、用户体验下降等一系列问题。本文将深入剖析开源项目**zero-to-production**(一个基于Rust的API开发框架)的错误类型设计与Result处理模式,带你掌握Rust错误处理的精髓。 读完本文,你将获得: - 自定义错误类型的分层设...

gitblog_01086的博客 935

‌Rust 错误处理:Result 与 Option 模式

显式优于隐式:所有可能失败的操作必须通过Result或Option暴露。模式匹配优先:使用match或?处理所有分支,避免unwrap。自定义错误类型:通过thiserror或anyhow实现更清晰的错误分类。

2501_93893138的博客 875

AI 辅助:Rust 错误处理模式:什么时候用 Result,什么时候该 panic

Rust 中可恢复错误应使用Result,不可恢复的逻辑错误才考虑panic。少用unwrap,为错误增加上下文,并根据应用层或库层选择合适的错误类型,是写生产级 Rust 的基础。

no1coder的博客 1098

Crate 级错误类型与 Result 别名:用 thiserror 打造生产级 Rust 错误处理(Rust for C Programmers)

本文是 RustTraining 仓库《Rust for C# Programmers》([csharp-book](https://link.gitcode.com/i/d9ef08e718d26557254402f4ac2a0678))第九章进阶篇的深度展开,核心讲解生产级 Rust 项目中最关键的错误处理模式:用 `thiserror` 定义一个 crate 级的错误枚举、通过 `Resul

gitblog_00431的博客 690

Rust 错误处理模式:从 Result 到 thiserror/anyhow 的生产级代码组织

/ 使用 thiserror 为库定义精确的错误类型// 调用方可以 match 具体变体,做出不同处理/// 数据库操作错误类型/// 每个变体对应一种具体的失败场景/// 连接失败:网络不可达或认证失败#[error("数据库连接失败: {source}")]#[source]},/// 查询超时:SQL 执行超过时间限制#[error("查询超时: {sql} 执行超过 {timeout_ms}ms")]},/// 数据未找到:查询条件无匹配记录。

no1coder的博客 3251

Rustlings 错误处理实战:用 Result、? 操作符与自定义错误类型构建稳健的 Rust 程序

本篇指南基于 rustlings 仓库中的 [13_error_handling](https://link.gitcode.com/i/0bd6d50a7b1a582348b07e5c41e1b546) 章节,完整讲解 Rust 可恢复错误的处理体系:从 `Result` 与 `Option` 的区别,到 `?` 操作符的错误传播、`main` 返回 `Result`、自定义错误枚举,再到用 `

gitblog_01160的博客 497

Rust错误处理模式:从Result到anyhow的工程实践

在系统编程领域,错误处理一直是区分优秀代码与平庸代码的关键。Rust通过类型系统强制开发者处理错误,这种设计哲学从根本上杜绝了"忽略错误"的可能性。本文将深入探讨Rust错误处理的核心模式,并分享工程实践中的专业思考。

gegegege0007的博客 1044
上一篇: Python函数式编程实战:从理论到生产环境
下一篇: Python内存管理深度解析:从GC到生产环境调优
第一程序员
博客等级 码龄1年 1万+粉丝 1827原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值