rust 强制转换
use std::ops::Deref; struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } //impl<T> Deref for MyBox<T> { // type Target = T; // // fn deref(&self) -> &T { // &self.0 // } //} fn hello(name: &str) { println!("Hello, {}!", name); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&m); }
cargo build Compiling hello_world v0.1.0 (/data2/rust/coercion2) warning: unused import: `std::ops::Deref` --> src/main.rs:1:5 | 1 | use std::ops::Deref; | ^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default error[E0308]: mismatched types --> src/main.rs:23:11 | 23 | hello(&m); | ^^ expected `str`, found struct `MyBox` | = note: expected reference `&str` found reference `&MyBox<std::string::String>` error: aborting due to previous error; 1 warning emitted For more information about this error, try `rustc --explain E0308`. error: could not compile `hello_world`. To learn more, run the command again with --verbose.
赞 (0)