【问题标题】:Rust: what is different in the slice clone method?Rust:切片克隆方法有什么不同?
【发布时间】:2023-01-15 09:54:24
【问题描述】:

来自这个有效的代码模板:

{ 
  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

克隆如何发起借用?

【问题讨论】:

    标签: rust slice borrow-checker borrow


    【解决方案1】:

    在您的第一个示例中,s 是一个&String,而String 实现了Clone,因此使用了clone(&self) 方法。

    在你的第二个例子中,s&[u8][u8]没有实现Clone。因此,您使用 blanket implementation 代替 &T,其中 T 是任何类型;也就是说,您正在克隆引用,而不是被引用的东西。结果是对同一事物的另一个引用,因此它仍然是借用。

    在这种情况下,解决方案是使用不同于.clone() 的方法来创建切片的自有副本。正如您所注意到的,Vec::from 有效,并为您提供 Vec<u8>;您也可以使用Box::from 来获得Box<[u8]>。您不能(当前)将原始的 [u8] 作为局部变量,因为它是未调整大小的类型,所以在这里使用 ::from 是因为您需要选择您拥有的副本的其他类型。

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 2023-03-20
      • 2021-06-29
      • 2014-02-17
      • 2010-10-22
      相关资源
      最近更新 更多