这是我的Cargo .

[package]
name = "tmp"
version = "0.1.0"
edition = "2021"

[dependencies]
chrono = "0.4.24"
chrono-tz = {version="0.8.2", optional = true}

[features]
my_feature = ["chrono-tz"]

以下是我的src/main.rs条建议:

#[cfg(feature = "some_feature")]
use chrono_tz::Tz;

#[cfg(feature = "some_feature")]
fn my_fn(tz: Tz){
    println!("tz is: {:?}", tz);
}


fn feature_function(tz: Option<Tz>) {
    match tz {
        #[cfg(feature = "some_feature")]
        Some(tz) => my_fn(tz),
        _ => (),
    }
}

fn main() {
    feature_function(None);
}

注意feature_function是如何接受tz: Optional<Tz>的,但是只有在启用了"SOME_FEATURE"时才会达到Some(tz)的情况.

因此,如果我没有启用"SOME_FEATURE",我希望能够用tz=None呼叫feature_function.

可以预见的是,这不会编译:

error[E0412]: cannot find type `Tz` in this scope
  --> src/main.rs:10:32
   |
10 | fn feature_function(tz: Option<Tz>) {
   |                                ^^ not found in this scope
   |
help: you might be missing a type parameter
   |
10 | fn feature_function<Tz>(tz: Option<Tz>) {
   |                    ++++

For more information about this error, try `rustc --explain E0412`.
error: could not compile `tmp` due to previous error

有没有什么技巧可以用来在feature_function中输入tz,这样如果没有启用"SOME_FEATURE",我仍然可以用tz=None呼叫feature_function

推荐答案

要确定Option<T>的大小,编译器必须知道T,因此,如果函数必须在您have to导入的两种情况下都具有相同的签名,则这两种情况下都是Tz. 如果不需要相同的签名,您可以使用相同的名称定义两个不同的函数:

enum NeedSomeFeatureForTz{}
#[cfg(not(feature = "some_feature"))]
fn feature_function(tz: Option<NeedSomeFeatureForTz>) {
    match tz {
        _ => (),
    }
}
#[cfg(feature = "some_feature")]
fn feature_function(tz: Option<Tz>) {
    match tz {
        Some(tz) => my_fn(tz),
        _ => (),
    }
}

Rust相关问答推荐

无需通过ASIO输入音频,并使用cpal进行反馈示例

如何将元素添加到向量并返回对该元素的引用?

如何使用Match比较 struct 中的值

rust 蚀生命周期 行为

为什么Rust函数的移植速度比C++慢2倍?

在执行其他工作的同时,从共享裁判后面的VEC中删除重复项

这是不是在不造成嵌套的情况下从枚举中取出想要的变体的惯用方法?

一种随机局部搜索算法的基准(分数)

如何修复数组中NewType导致的运行时开销

如何迭代存储在 struct 中的字符串向量而不移动它们?

为什么Rust中无法推断生命周期?

Rust中的位移操作对范围有什么影响?

返回引用字符串的future

RAII 模式的 Rust 解决方案,用于在 new() 和 drop() 上修改另一个对象

没有通用参数的通用返回

如何在 nom 中构建负前瞻解析器?

制作嵌套迭代器的迭代器

为什么我可以在没有生命周期问题的情况下内联调用 iter 和 collect?

如何阅读 HttpRequest 主体

为什么 Rust 中的关联类型需要明确的生命周期注释?