rust 即使未启用功能标志,也使用在功能标志后面导入的类型

sy5wg1nm  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(161)

这是我的货物

[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

j8ag8udp

j8ag8udp1#

要确定Option<T>的大小,编译器必须知道T,所以如果函数必须在所有特性中具有相同的签名,那么在两种情况下都必须导入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),
        _ => (),
    }
}

相关问题