string - 返回引用新 &str 的结构

标签 string reference rust

我目前正在编写一个程序,有时我必须处理一个包含 &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/

相关文章:

string - 从字符串计算 JSTL 表达式

visual-studio - 添加对源代码控制下的产品的 Visual Studio 引用

c++ - 通过引用传递变量并构造新对象

asynchronous - 将请求正文转发到 Actix-Web 中的响应

rust - 在 Rust 中取消引用引用向量

c++ - 反转非 ASCII 字符的字符串

PHP:如何从字符串中获取特定单词

windows - 带有大文本文件的 Perl "out of memory"

java - Android:使用findViewById时需要引用 View ?

algorithm - 康威的生命游戏应该有无限 map 还是应该有限制?