Rust 自定义条件

有部分条件如 target_os 是由 rustc 隐式地提供的,但是自定义条件必须使用 --cfg 标记来传给 rustc。

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

fn main() {
    conditional_function();
}

试试不使用自定义的 cfg 标记会发生什么:

$ rustc custom.rs && ./custom
No such file or directory (os error 2)

使用自定义的 cfg 标记:

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

泛型(generic)是关于泛化类型和函数功能,以扩大其适用范围的话题。泛型极大地减少了代码的重复,但它自身的语法很要求细心。也就是说,采用泛型意味着仔细地指定泛型类型具体化时,什么样的具体类型是合法的。泛型最简单和常用的用 ...