[英]Forcing a borrow with the `Into` trait
struct Foo(i32);
impl<'a> Into<i32> for &'a Foo {
fn into(self) -> i32 {
self.0
}
}
fn test<I: Into<i32>>(i: I) {
let n: i32 = i.into();
println!("{}", n);
}
fn main() {
let f = Foo(42);
test(&f);
}
This works but just looking at test
这有效,但只是看看test
fn test<I: Into<i32>>(i: I) {
let n: i32 = i.into();
println!("{}", n);
}
The function can access both a borrow and a move/copy depending on how the Into
trait is implemented.该函数可以访问借用和移动/复制,具体取决于Into
特征的实现方式。
impl<'a> Into<i32> for &'a Foo
// vs
impl Into<i32> for Foo
Now the user could try to call test like test(f);
现在用户可以尝试调用 test 之类的test(f);
instead of test(&f);
而不是test(&f);
and would receive the following error message.并会收到以下错误消息。
error[E0277]: the trait bound `i32: std::convert::From<Foo>` is not satisfied
--> <anon>:16:5
|
16 | test(f);
| ^^^^ trait `i32: std::convert::From<Foo>` not satisfied
|
Would it be possible to always force a borrow?是否可以始终强制借款? Something similar to this类似的东西
fn test<I: Into<i32>>(i: &I) {
let n: i32 = i.into();
println!("{}", n);
}
So that the user would get an error message similar to, "Expected &XX but found YY".这样用户会收到类似于“预期为 &XX 但找到 YY”的错误消息。
A where
-clause works here by specifying the lifetime: where
-clause 通过指定生命周期在这里起作用:
fn test<'a, I>(i: &'a I) where &'a I: Into<i32> {
let n: i32 = i.into();
println!("{}", n);
}
Now when you attempt to build with test(f);
现在,当您尝试使用test(f);
进行构建时test(f);
, the message is clearer: ,信息更清晰:
error[E0308]: mismatched types
--> src/main.rs:16:10
|
16 | test(f);
| ^
| |
| expected `&Foo`, found struct `Foo`
| help: consider borrowing here: `&f`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.