提问人:inyourface3445 提问时间:3/8/2023 更新时间:3/9/2023 访问量:174
在 Rust 中将字符串转换为 &str [duplicate]
Convert String to &str in Rust [duplicate]
问:
我正在尝试将 a 转换为 .但问题是 rust 总是会抛出这个错误:String
&str
error[E0515]: cannot return value referencing local variable `contents`
--> src/utils.rs:111:5
|
72 | let contents = &contents[..];
| -------- `contents` is borrowed here
...
111 | result
| ^^^^^^ returns a value referencing data owned by the current function
For more information about this error, try `rustc --explain E0515`.
如何将变量转换为 &str?
答:
0赞
inyourface3445
3/9/2023
#1
事实证明,那时候最好回来.这解决了我的问题。感谢 cafce25 提供这个想法。Vec<String>
Vec<&str>
评论
1赞
Roger Filmyer
3/9/2023
如果你正在为 rust 生命周期而苦苦挣扎,一个安全的经验法则是编写接受引用和返回值的函数(所以在这种情况下,取 s 并返回 s)&str
String
评论
String
Vec<&str>
Vec<String>
String