我有以下结构:
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()
}
}