我正在尝试从 Rust 官方网站上的 Rust 书中编译以下代码。
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}
fn main() {
let s = "Hello".to_string();
takes_slice(&s);
}
在编译时,它抛出以下错误
/devl/rust/bc_09/src/main.rs:7:17: 7:19 error: mismatched types: expected
&str
, found&collections::string::String
(expected str, found struct collections::string::String)/devl/rust/bc_09/src/main.rs:7 takes_slice(&s); ^~ error: aborting due to previous error Could not compile
hello_world
.
这是我正在运行的 Rust 版本:rustc 1.0.0-nightly (44a287e6e 2015-01-08 17:03:40 -0800)
最佳答案
用 Rust 的术语来说,那是 nightly 的一个非常旧的版本!足够老了 &String
-> &str
强制不可用。您只需要升级到更新的版本。
关于string - 无法将 &String 强制转换为 &str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28526850/