考虑以下代码:
use std::ops::Add;
trait Trait
where Self::Assoc: Add<Self::Assoc, Output=Self::Assoc>
+ for <'a> Add<&'a Self::Assoc, Output=Self::Assoc>
{
type Assoc;
fn get(&self) -> Self::Assoc;
}
fn add1<T: Trait>(x: T, y: T) -> T::Assoc {
x.get() + y.get()
}
Run Code Online (Sandbox Code Playgroud)
这无法编译:
error[E0308]: mismatched types
--> src/lib.rs:12:15
|
12 | x.get() + y.get()
| ^^^^^^^
| |
| expected reference, found associated type
| help: consider borrowing here: `&y.get()`
|
= note: expected reference `&<T as Trait>::Assoc`
found associated type `<T as Trait>::Assoc`
Run Code Online (Sandbox Code Playgroud)
我可以通过明确指定我想要使用的特征来解决这个问题:
fn …Run Code Online (Sandbox Code Playgroud) 场景如下:我的 crate 依赖于num-bigint,并且可选依赖于rand:
[dependencies]
num-bigint = { version = "0.2" }
rand = { version = "0.7", optional = true }
Run Code Online (Sandbox Code Playgroud)
什么时候 rand在我的箱子上被禁用时,一切都很好。
当rand在我的箱子上启用时,我希望也启用该rand功能num-bigint。我怎样才能做到这一点?
这是我尝试过的:
[target.'cfg(feature = "rand")'.dependencies]
num-bigint = { version = "0.2", features = ["rand"] }
Run Code Online (Sandbox Code Playgroud)
这有效,但我收到此警告:
warning: Found `feature = ...` in `target.'cfg(...)'.dependencies`. This key is not supported for selecting dependencies and will not work as expected. Use the [features] section instead: https://doc.rust-lang.org/cargo/reference/features.html
Run Code Online (Sandbox Code Playgroud)
我应该忽略警告,还是有更好的方法来做到这一点?我检查了该网页,但找不到任何有用的信息。