我目前正在编写一个程序,有时我必须处理一个包含 &str
值的结构。让我们考虑一下它的外观:
struct Book<'a> {
url: &'a str,
}
我有一个函数可以从远程存储中获取一本书并返回指向该书的 URL,如下所示:
fn fetch_book<'a>(id: u64) -> Book<'a> {
// do some stuff to get a 'key' variable that allows to access the book
Book {
// Here we turn the formatted String into an &str
url: &format!("https://<ip-address>/books?id={}&key={}", id, key)
}
}
这个函数不会编译,因为 Rust 告诉我们正在返回一个引用当前函数拥有的数据的值。
那么,我该怎么做才能使这个函数正常工作(不会变得不安全
)?
最佳答案
正如@DenysSéguret 在评论中指出的那样:
At the end of the function, the values that are created are either dropped or moved. If you don't move the
str
(ie return it in an owning structure), it's dropped and references to it makes no sense anymore.
此外,根据 this question在 Rust 的用户论坛上发布,确实不可能从“新生成的”字符串返回 &str
。
关于string - 返回引用新 &str 的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58043281/