Rust:切片克隆方法有什么不同?

Rust: what is different in the slice clone method?

提问人:Frank Schwidom 提问时间:1/14/2023 最后编辑:Frank Schwidom 更新时间:1/14/2023 访问量:90

问:

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

{ 
  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

克隆如何发起借贷?

切片 borrow-checker borrow

评论


答:

2赞 kaya3 1/14/2023 #1

在第一个示例中,是 ,并实现 ,因此使用了该方法。s&StringStringCloneclone(&self)

在第二个示例中,是 ,并且不实现 。因此,您正在对 where is any 类型使用一揽子实现;也就是说,您正在克隆引用,而不是被引用的事物。结果是对同一事物的另一次引用,因此它仍然是借用的。s&[u8][u8]Clone&TT

在这种情况下,解决方案是使用与创建切片的自有副本不同的方法。正如你所注意到的,工作,并给你一个;您还可以使用获取 .您(目前)无法将 raw 作为局部变量获取,因为这是一个未调整大小的类型,因此在此处使用是因为您需要选择您拥有的副本将是什么其他类型。.clone()Vec::fromVec<u8>Box::fromBox<[u8]>[u8]::from