这是我的货物
[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
?
1条答案
按热度按时间j8ag8udp1#
要确定
Option<T>
的大小,编译器必须知道T
,所以如果函数必须在所有特性中具有相同的签名,那么在两种情况下都必须导入Tz
。如果不需要相同的签名,则可以定义两个同名的不同函数: