返回格式化字符串作为字节的引用



我有以下结构:

struct CompareUrl {
repo: String,
left: String,
right: String,
}

我希望这个结构以字节为单位返回它自己。

impl CompareUrl {
pub fn as_bytes(&self) -> &[u8] {
format!(
"https://github.com/{}/compare/{}...{}",
self.repo,
self.left,
self.right
).as_bytes()
}
}

但它抱怨所有权:

cannot return reference to temporary value
returns a reference to data owned by the current function

它似乎对(&str).as_bytes()有效,但对(String).as_bytes()无效。我的尝试是这样解决这个问题:

impl CompareUrl {
pub fn as_bytes(&self) -> &[u8] {
format!(
"https://github.com/{}/compare/{}...{}",
self.repo,
self.left,
self.right
).as_str().as_bytes()
}
}

但它也提出了同样的错误。我该如何解决?

不能像format!宏生成的String那样返回对函数拥有的值的引用,因为当函数返回时,它会被丢弃,并且引用将无效。使用into_bytes方法将String转换为拥有的字节Vec

impl CompareUrl {
pub fn as_bytes(&self) -> Vec<u8> {
format!(
"https://github.com/{}/compare/{}...{}",
self.repo,
self.left,
self.right
).into_bytes()
}
}

最新更新