[英]Rust: what is different in the slice clone method?
來自這個有效的代碼模板:
{
fn f3( _s : &String) {}
fn f( s : &String) -> impl FnMut() {
let s2 = s.clone();
move || f3( &s2)
}
let mut f2 = f( &"123".to_string());
f2();
}
如果我這樣修改代碼:
{
fn f3( _s : &[u8]) {}
fn f( s : &[u8]) -> impl FnMut() {
// let s2 = s.clone(); // don't work
let s2 = Vec::from(s);
move || f3( &s2[..])
}
let mut f2 = f( &vec![1u8][..]);
f2();
}
我不能使用“let s2 = s.clone();”。 這會帶來錯誤消息:
1169 | fn f( s : &[u8]) -> impl FnMut() {
| ------------ this return type evaluates to the `'static` lifetime...
1170 | let s2 = s.clone();
| ^^^^^ ...but this borrow...
|
note: ...can't outlive the anonymous lifetime #1 defined on the function body at 1169:3
克隆如何發起借用?
在您的第一個示例中, s
是&String
,而String
實現了Clone
,因此使用了clone(&self)
方法。
在您的第二個示例中, s
是&[u8]
,並且[u8]
沒有實現Clone
。 因此,您正在使用&T
的一攬子實現,其中T
是任何類型; 也就是說,您正在克隆引用,而不是被引用的東西。 結果是對同一事物的另一個引用,因此它仍然是借用。
這種情況下的解決方案是使用不同於.clone()
的方法來創建切片的自有副本。 正如您所注意到的, Vec::from
有效,並為您提供了一個Vec<u8>
; 您還可以使用Box::from
獲取Box<[u8]>
。 您不能(當前)將原始[u8]
作為局部變量獲取,因為它是未調整大小的類型,因此在這里使用::from
是因為您需要選擇您擁有的副本將是什么其他類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.