Rust 条件函数编译

RustRustBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,我们有一段代码片段,其中包含一个名为 conditional_function() 的函数,但只有在使用 --cfg 标志将一个名为 some_condition 的自定义条件传递给 rustc 时,它才会被编译和执行。

注意:如果实验没有指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,通过 rustc main.rs &&./main 来编译和运行它。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") subgraph Lab Skills rust/function_syntax -.-> lab-99343{{"Rust 条件函数编译"}} rust/expressions_statements -.-> lab-99343{{"Rust 条件函数编译"}} end

自定义

target_os 这样的一些条件是由 rustc 隐式提供的,但自定义条件必须使用 --cfg 标志传递给 rustc

#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!");
}

fn main() {
    conditional_function();
}

尝试在不使用自定义 cfg 标志的情况下运行此代码,看看会发生什么。

使用自定义 cfg 标志时:

$ rustc --cfg some_condition custom.rs && ./custom
condition met!

总结

恭喜你!你已经完成了“自定义”实验。你可以在LabEx中练习更多实验来提升你的技能。