Rust宏编程详解:从声明式到过程宏的完整指南

Rust编程基础教程:宏和元编程 1.背景介绍 Rust是一种现代系统编程语言,它具有内存安全、并发原语和类型系统等特点。Rust编程语言的宏和元编程功能是其强大的编程工具之一,可以帮助开发者更高效地编写代码。本文将详细介绍Rust编程基础教程的宏和元编程,包括其核心概念、算法原理、具体操作步骤、数学模型公式、代码实例以及未来发展趋势。 阅读详情

Rust宏编程详解:从声明式到过程宏的完整指南

引言

宏编程是Rust中非常强大的特性,允许我们在编译时生成代码。作为从Python转向Rust的后端开发者,我发现Rust的宏系统与Python的装饰器和元类有很大不同,它更加类型安全且功能强大。本文将深入探讨Rust的宏编程,帮助你理解和使用声明式宏、过程宏等高级特性。

一、宏的概念

1.1 什么是宏

宏是一种元编程工具,允许我们在编译时生成代码。与函数不同,宏在编译期展开,可以处理任意数量的参数。

1.2 宏的优势

  1. 代码复用:避免重复代码
  2. 编译时计算:在编译期完成计算
  3. 类型安全:在编译时检查类型
  4. 领域特定语言:创建DSL

二、声明式宏

2.1 基本语法

macro_rules! say_hello {
    () => {
        println!("Hello, World!");
    };
}

fn main() {
    say_hello!();
}

2.2 带参数的宏

macro_rules! print_sum {
    ($x:expr, $y:expr) => {
        println!("Sum: {}", $x + $y);
    };
}

fn main() {
    print_sum!(2, 3); // 输出: Sum: 5
}

2.3 重复模式

macro_rules! vec_strs {
    ($($x:expr),*) => {
        vec![$(stringify!($x)),*]
    };
}

fn main() {
    let v = vec_strs!(a, b, c);
    println!("{:?}", v); // 输出: ["a", "b", "c"]
}

2.4 嵌套宏

macro_rules! debug {
    ($val:expr) => {
        println!("{} = {:?}", stringify!($val), $val);
    };
    ($($val:expr),*) => {
        $(debug!($val);)*
    };
}

fn main() {
    let x = 42;
    let y = "hello";
    debug!(x, y);
}

三、过程宏

3.1 派生宏

use derive_more::Add;

#[derive(Add, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p1 = Point { x: 1, y: 2 };
    let p2 = Point { x: 3, y: 4 };
    let p3 = p1 + p2;
    println!("{:?}", p3); // 输出: Point { x: 4, y: 6 }
}

3.2 属性宏

#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
    // 解析属性参数
    let route_path = parse_macro_input!(attr as String);
    
    // 生成包装函数
    quote! {
        #[get(#route_path)]
        #item
    }
}

#[route("/users")]
async fn get_users() -> Json<Vec<User>> {
    // 处理逻辑
}

3.3 函数式宏

#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
    let query = parse_macro_input!(input as String);
    
    quote! {
        // 生成SQL执行代码
        sqlx::query(#query)
    }
}

let users = sql!("SELECT * FROM users WHERE id = 1").fetch_all(&pool).await?;

四、宏的高级用法

4.1 使用quote生成代码

use quote::quote;
use syn::parse_macro_input;

#[proc_macro]
pub fn make_struct(input: TokenStream) -> TokenStream {
    let name = parse_macro_input!(input as syn::Ident);
    
    let expanded = quote! {
        struct #name {
            id: i32,
            name: String,
        }
        
        impl #name {
            fn new(id: i32, name: &str) -> Self {
                Self {
                    id,
                    name: name.to_string(),
                }
            }
        }
    };
    
    expanded.into()
}

make_struct!(User);

let user = User::new(1, "Alice");

4.2 解析复杂语法

#[proc_macro]
pub fn build(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as syn::Expr);
    
    match ast {
        syn::Expr::Lit(syn::ExprLit { lit, .. }) => {
            match lit {
                syn::Lit::Str(s) => {
                    let value = s.value();
                    quote! { #value }
                }
                _ => panic!("Expected string literal"),
            }
        }
        _ => panic!("Expected literal expression"),
    }
    .into()
}

4.3 条件编译宏

#[cfg(target_os = "linux")]
macro_rules! platform_specific {
    () => {
        println!("Running on Linux");
    };
}

#[cfg(target_os = "windows")]
macro_rules! platform_specific {
    () => {
        println!("Running on Windows");
    };
}

fn main() {
    platform_specific!();
}

五、实战:自定义派生宏

5.1 创建派生宏项目

cargo new derive_macro_example --lib

5.2 添加依赖

[lib]
proc-macro = true

[dependencies]
syn = "2.0"
quote = "1.0"
proc-macro2 = "1.0"

5.3 实现宏

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    
    let expanded = quote! {
        impl #name {
            pub fn builder() -> #name Builder {
                #name Builder::default()
            }
        }
        
        #[derive(Default)]
        pub struct #name Builder {
            #(
                #fields
            )*
        }
        
        impl #name Builder {
            pub fn build(self) -> #name {
                #name {
                    #(
                        #field_assignments
                    )*
                }
            }
        }
    };
    
    expanded.into()
}

#[derive(Builder)]
struct User {
    id: i32,
    name: String,
    email: String,
}

let user = User::builder()
    .id(1)
    .name("Alice")
    .email("alice@example.com")
    .build();

六、宏的最佳实践

6.1 宏命名规范

// 好:使用snake_case
macro_rules! vec_strs {
    // ...
}

// 好:使用感叹号结尾表示宏
macro_rules! log_info {
    // ...
}

6.2 避免过度使用宏

// 不好:宏过于复杂难以理解
macro_rules! complex_macro {
    // 几百行代码...
}

// 好:使用函数或trait代替
fn complex_function() {
    // 清晰的逻辑
}

6.3 添加文档

/// 创建一个包含指定元素的向量
///
/// # Examples
///
/// ```
/// let v = vec_strs!(a, b, c);
/// assert_eq!(v, ["a", "b", "c"]);
/// ```
macro_rules! vec_strs {
    ($($x:expr),*) => {
        vec![$(stringify!($x)),*]
    };
}

七、宏的调试

7.1 使用cargo expand

cargo install cargo-expand
cargo expand --example my_example

7.2 添加调试信息

macro_rules! debug_macro {
    ($($arg:tt)*) => {
        #[cfg(debug_assertions)]
        {
            println!("Macro expanding: {}", stringify!($($arg)*));
        }
        // 实际逻辑
    };
}

八、总结

Rust的宏系统是一个强大的元编程工具,允许我们在编译时生成代码。通过掌握声明式宏和过程宏,我们可以创建更加简洁、可维护的代码。

关键要点:

  1. 声明式宏:使用macro_rules!定义,适合简单的代码生成
  2. 过程宏:使用proc_macro crate,适合复杂的代码转换
  3. 使用quote和syn:简化宏的编写
  4. 避免过度使用:宏应该用于代码复用,而不是滥用
  5. 添加文档:提高宏的可使用性

从Python转向Rust后,我发现Rust的宏系统更加类型安全和强大,虽然学习曲线较陡,但一旦掌握,能够大大提高开发效率。

延伸阅读

  • Rust官方宏指南
  • syn crate文档
  • quote crate文档
  • proc_macro官方文档
【Rust宏编程】Rust有关宏编程底层原理解析与应用实战 Rust的宏系统是其语言中最强大但也最复杂的特性之一。 与C/C++的简单文本替换宏不同,Rust提供了两种完全集成到语言中的宏系统:声明式宏(declarative macros)和过程式宏(procedural macros)。 宏在Rust中扮演着至关重要的角色,它们允许开发者: - 消除重复代码 - 创建领域特定语言(DSL) - 在编译时生成代码 - 实现编译期计算 阅读详情

相关推荐

3、Rust宏编程:从基础到实践

本文深入讲解了Rust中的宏编程,涵盖声明式宏和过程宏的基本概念与实践技巧。内容包括宏的语法结构、匹配器与转录器的使用、元变量的定义、宏的导出与使用方法,以及宏在减少代码重复和提升开发效率方面的应用。同时,文章通过具体示例展示了如何利用宏简化数据库查询等复杂任务,并探讨了宏编程在实际项目中的价值。

vvv99的博客 67

rust宏(macro)详解

rust宏解析

白嫩豆腐 2477

1、深入探索Rust宏编程

本文深入介绍了Rust宏编程的基础知识、声明式宏和过程式宏的实际应用。内容涵盖元编程的概念、宏的使用场景、声明式宏的语法和用例,以及过程式宏的编写和调试方法。通过实例讲解了如何创建向量宏、实现derive宏、属性宏和类函数宏,并探讨了宏的测试、错误处理和最佳实践。适合熟悉Rust基础并希望掌握宏编程的开发者阅读。

vvv99的博客 110

Rust 中的宏

宏(macro) 是 Rust 中的一种高级特性,Rust 中的宏分为两种: 声明性宏(declarative macros) 程序宏(procedural macros) Custom #[derive] macros Attribute-like macros Function-like macros 宏与函数的区别 函数不能接收任意多个参数,而宏可以。 函数不能操作语法单元,而宏可以。从根本上说,宏是用来生成代码的。 函数在编译之前不需要特殊处理,声明性宏需要在编译之前进行展开,展开之后代

花落花开的博客 8383

FairyGUI编辑器自定义菜单扩展插件

本文涉及到的软件有:FairyGUI,VSCode代码环境涉及到了:LuaVSCode插件:EmmyLua在编写FairyGUI编辑器菜单前,了解一下FairyGUIEditor的API会有效的帮助我们解决很多问题。FairyGUI的扩展是通过编辑器自带的插件功能实现的,插件中我使用的是lua环境模板。导入编辑器的LuaAPI,文件可以在FairyGUI-Editor源码的插件目录中找到。接下来将通过功能来说明对应的API作用。

Aili_Xiao的博客 4501

基于继电器与三极管的自动水泵控制器DIY:从电路原理到PCB制作实战

继电器作为一种利用电磁原理实现电路通断控制的电气开关,其核心价值在于通过小电流信号控制大电流负载,实现强弱电之间的安全隔离。在自动化控制领域,继电器常与三极管等半导体器件配合,构成驱动电路,将微弱的传感器信号放大,从而可靠地控制电机、水泵等执行机构。这种组合技术广泛应用于工业控制、智能家居及各类电子DIY项目中,例如实现水箱水位的自动检测与控制。本文将以一个典型的自动水泵控制器项目为例,深入剖析如何利用继电器与三极管搭建水位检测与驱动电路,并详细讲解从电路设计、PCB自制(热转印法)到系统调试的完整工程实践

weixin_31774841的博客 348

Rust语言中的宏

在 Rust 中,宏(macro)是一种强大的工具,可以通过生成代码来实现重复的模式、避免冗余,或增强语言的表达能力。和。

weixin_46063534的博客 868

国科大学习资料--机器学习方法与应用(叶齐祥)-期末考试题整理

国科大学习资料–机器学习方法与应用-期末考试题整理 ============================================================================================================================================================================================ =======================================

无名何许人的博客 2852

【Rust 基础篇】Rust宏:代码生成的黑魔法

在Rust中,宏是一种特殊的函数,可以使用关键字来定义。// 宏规则 // ... }其中,macro_name是宏的名称,宏规则是一系列模式匹配和替换的规则,用于匹配输入的代码片段并生成相应的代码片段。除了使用#[derive]宏,我们还可以自定义属性宏,用于处理更复杂的场景。让我们创建一个简单的自定义属性宏,用于检查函数的参数是否大于10。// 处理输入的代码,并生成新的代码 // ... }在上述例子中,我们使用proc_macro模块导入了和宏,然后定义了一个名为check_arg的自定义属性宏。

繁依Fanyi的博客 2392

uniapp支付宝/钉钉小程序ref为undefined的解决方案 `uniapp 支付宝小程序 ref undefined` `uniapp 钉钉小程序 组件ref获取失败` `uniapp 支付宝

如果你在uniapp 开发支付宝小程序或钉钉小程序时,遇到ref始终为undefined的问题,十有八九就是没开启 component2。所以记住一句话:👉支付宝/钉钉小程序要想用 ref,必须在里加。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1224

RK3588开发笔记-mipi csi接口imx415摄像头调试记录

摘要:本文详细介绍了RK3588开发板适配SONY IMX415 MIPI CSI摄像头的调试过程。从硬件环境准备(包括RK3588核心板、IMX415模块连接及测试工具)、软件环境配置(Linux 5.10内核、驱动状态确认),到设备树关键配置(MIPI链路、GPIO引脚、电源域等)都进行了详细说明。调试过程中通过dmesg日志、media-ctl拓扑分析等工具验证了摄像头驱动加载和图像采集功能。最终实现了800万像素高清图像采集,总结了硬件连接验证、信号完整性优化等关键经验,为类似MIPI摄像头调试提供

flypig has a dream! 886

Rust Rosetta Code宏编程:从声明式宏到过程宏的进阶指南

Rust Rosetta Code项目通过实现各种算法和问题展示了Rust语言的强大能力,其中宏编程是提升代码复用性和表现力的核心技术。本文将带你探索Rust宏编程的完整路径,从基础的声明式宏到高级的过程宏,掌握如何利用宏简化复杂逻辑并编写出更优雅的Rust代码。 ## 声明式宏:Rust宏编程的入门钥匙 🗝️ 声明式宏(Declarative Macros)是Rust中最常用的宏类型,通过

gitblog_00481的博客 374

python基础知识补充

1. jupyter notebook 解释 2. ipython 魔法命令 3. latex in Markdown cell(在markdown里面编写数学公式) 4. jupyter notebook功能扩展:安装Nbextension 5. python解释与运行 6. 垃圾回收(计数机制与分代回收机制) 7. 名字空间与局部作用域L和全局作用域G 8. 小整数缓存区与字符驻留 9. Statement &Expression 10. 调试

weixin_43178406的博客 1万+

Rust宏编程完全指南:从基础到高级的元编程艺术

本文深入探讨了Rust强大的宏系统,包括声明式宏和过程式宏两大类型。声明式宏基于模式匹配和卫生性设计,适合处理重复代码模式;而过程式宏则提供了更灵活的编译期代码生成能力,可实现派生宏、属性宏等多种功能。文章还介绍了高级宏技巧如递归宏和TT咀嚼器模式,并提供了调试宏的方法。Rust宏系统是其元编程能力的核心,能显著提升代码表现力和开发效率。

厚积薄发的博客 1992

Android 14.0 开机广播接收慢广播延迟问题分析

在14.0的系统rom定制化开发中,在某些时候在接收开机广播的时候发现,过了一分钟才收到开机广播,接下来就需要分析下 开机广播的相关分发机制,来处理下相关问题

安卓兼职framework和app工程师的博客 632

2026年VIVO嵌入式岗位高频面试题(含参考答案)

摘要:VIVO嵌入式岗位考核涵盖智能手机、IoT设备、芯片适配等方向,重点考察硬件底层交互、RTOS/Linux开发、C/C++功底与问题排查能力。题目按优先级排序,分硬件架构、RTOS、C/C++、数据结构、Linux实践、行业认知6大模块,共40道题。硬件部分涉及中断、ARM架构、加速技术、BSP开发等;RTOS部分区分硬/软实时系统;C/C++部分侧重内存管理、位操作;Linux部分考察常用命令;行业部分关注鸿蒙等系统理念。题目设计贴合实际工作场景,全面评估嵌入式开发能力。

Open 52

Rust宏编程:从声明宏到过程宏的进阶指南

宏编程是现代编程语言中实现元编程的核心技术,通过在编译期进行代码生成和转换,可以显著提升开发效率和代码复用性。Rust语言提供了声明宏(macro_rules!)和过程宏两套系统,前者基于模式匹配实现轻量级代码生成,后者则通过操作语法树实现更复杂的元编程逻辑。在编译器优化和零成本抽象场景下,宏技术能生成高度优化的特化代码,同时保持类型安全性。典型应用包括构建类型安全的SQL查询(如sqlx框架)、实现领域特定语言(DSL)以及创建高性能矩阵运算等。理解tt(token tree)匹配、卫生性机制以及syn/

weixin_33507732的博客 201

深度学习工具包 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")

teach-rs宏编程教学:如何编写可重用的代码生成器

teach-rs是一个模块化、可重用的Rust大学课程项目,其中宏编程作为Crate工程设计的重要模块,为开发者提供了强大的代码生成能力。本文将带你快速掌握宏编程的核心概念与实践技巧,帮助你编写可重用的代码生成器。 ## 为什么宏编程是Rust开发者的必备技能? 在Rust开发中,宏(Macro)是一种元编程工具,它允许你在编译时生成代码,从而减少重复劳动并提高代码的可维护性。teach-rs

gitblog_00424的博客 811

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

【译】Rust宏:教程与示例(一) - Rust声明式宏,看完本文就会写!

原文标题:Macros in Rust: A tutorial with examples 原文链接:https://blog.logrocket.com/macros-in-rust-a-tutorial-with-examples/ 公众号: Rust 碎碎念 翻译 by: Praying 知乎:https://www.zhihu.com/column/c_1186237256184029184 感谢Praying大佬的翻译。读完此篇教程,你应该就明白如何编写Rust声明式宏了。 在本文中,我们将会.

你好,PurePeace! 5655

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Crabtime实战指南:从基础到高级的Rust宏编程技巧

Crabtime是一个功能强大的Rust宏编程工具,它为开发者提供了介于`macro_rules!`和过程宏之间的解决方案,兼具易用性和灵活性。本文将带你从基础到高级,掌握Crabtime宏编程的核心技巧,让你的Rust代码更加简洁高效。 ## 📚 Crabtime简介:Rust宏编程的新选择 在Rust生态中,宏编程主要有两种方式:传统的`macro_rules!`和更强大的过程宏(Pro

gitblog_00004的博客 538

RustTraining 宏编程实战:从 C/C++ 预处理器到 Rust 声明式宏、派生宏与过程宏的完整迁移指南

> 本文是 RustTraining 仓库中《Rust for C/C++ Programmers》课程([c-cpp-book](https://link.gitcode.com/i/0e93e3aea50b671c21390d398205c1cd))第 19 章的系统化展开。核心主题是:Rust 宏体系(`macro_rules!` 声明式宏、`#[derive]` 派生宏、属性宏、过程宏)如

gitblog_00403的博客 416

blog_os宏编程:编译时代码生成技巧

在操作系统开发领域,编译时代码生成(Compile-time Code Generation)是一项至关重要的技术。当你在Rust中编写一个操作系统内核时,经常会遇到需要重复性代码、硬件抽象层接口定义、或者特定架构相关的底层操作。手动编写这些代码不仅繁琐,而且容易出错。 blog_os项目通过巧妙的宏编程技术,展示了如何在编译时自动生成这些重复性代码,从而提高开发效率、减少错误,并保持代码的清晰...

gitblog_00896的博客 1081

10-Rust 宏编程(声明式宏 + 过程宏 + syn/quote + 宏调试 + 自定义序列化宏)

本文深入讲解 Rust 宏编程核心知识,涵盖声明式宏(macro_rules!)、过程宏(派生宏、函数宏、属性宏)、syn 和 quote 库使用、宏调试技巧、实战自定义序列化宏等核心内容。每个知识点配有完整代码示例、对比表格、实战场景及常见问题解答,帮助开发者掌握 Rust 元编程能力。

2301_78939167的博客 272

Macro宏编程

如果我们要使用一个叫HelloMacro的特征,一种方法是首先,创建一个名叫hello_macro的工程,然后在src/lib.rs中定义过程宏所需的HelloMacro特征和其关联函数,接着是定义过程宏,宏所在的包名要求必须以derive为后缀,并且要放在单独的包中,因此再在项目根目录下lib包根。最后是完成主体代码//hello_macro 项目的目录结构├── src├── src└── lib.rs# 也可以使用下面的相对路径。

2301_79967122的博客 1331

RustTraining 宏编程实战:从 macro_rules! 到 syn + quote 的过程宏

> 本文是 RustTraining 开源训练仓库中 [rust-patterns-book](https://link.gitcode.com/i/4d54b90ac75429c595a9d7e2d648a49e) 第 13 章的完整展开,系统讲解 Rust 宏系统的两大分支——声明式宏(`macro_rules!`)与过程宏(derive / attribute / function-like

gitblog_00007的博客 498

Rust for C 开发者宏入门:从 `!` 后缀到 `macro_rules!` 与过程宏的完整指南

> 本文是 [RustTraining 仓库](https://link.gitcode.com/i/f04424d7720c13cf96a1c707685ccb9d) 中《Rust for C# Programmers》训练书第 12 章的延伸专题([Macros Primer](https://link.gitcode.com/i/c784e3565c4db3e36a8a12d96771a74

gitblog_01192的博客 549
上一篇: Python数据可视化实战:从Matplotlib到Plotly的完整指南
下一篇: Python机器学习模型部署实战:从训练到生产环境
第一程序员
博客等级 码龄1年 1万+粉丝 1827原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值