Rust 如何克隆盒子<;CustomStruct>;当我不断得到;没有名为“克隆”的方法;?

Rust 如何克隆盒子<;CustomStruct>;当我不断得到;没有名为“克隆”的方法;?,rust,Rust,我想克隆头,它是一个框: 让mut node=Some((*head.clone()); 以下是完整的代码(): 使用std::boxed::Box; 发布结构列表{ 酒吧老板:选择, 酒吧规模:u64, } impl列表{ pub fn new()->List{ 返回列表{ 标题:选项::无, 尺寸:0, }; } 发布fn推回(&mut self,数据:T){ 火柴头{ 一些(头)=>{ 让mut node=Some(*head.clone()); while(*(node).unwrap

我想克隆
,它是一个

让mut node=Some((*head.clone());
以下是完整的代码():

使用std::boxed::Box;
发布结构列表{
酒吧老板:选择,
酒吧规模:u64,
}
impl列表{
pub fn new()->List{
返回列表{
标题:选项::无,
尺寸:0,
};
}
发布fn推回(&mut self,数据:T){
火柴头{
一些(头)=>{
让mut node=Some(*head.clone());
while(*(node).unwrap()).next.is_some(){
node=(*node.unwrap()).next;
}
node.unwrap().next=Some(Box::new(node::new(data));
}
无=>{
self.head=Some(Box::new(Node::new(data));
}
}
}
}
#[衍生(克隆)]
发布结构节点{
下一步:选择,
pub值:T,
}
impl节点{
pub fn new(v:T)->节点{
节点{
下一步:选项::无,
值:v,
}
}
}
编译器一直说方法
clone
存在,但未满足以下特征界限:

error[E0599]:在当前作用域中找不到类型为`std::boxed::Box`的名为`clone`的方法
-->src/lib.rs:19:45
|
19 |让mut node=Some(*head.clone());
|                                             ^^^^^
|
=注意:方法“clone”存在,但未满足以下特征界限:
`节点:std::clone::clone`
`std::boxed::Box:std::clone::clone`
=帮助:只有在trait已实现且在范围内时,才能使用trait中的项
=注意:以下特征定义了一个“克隆”项,您可能需要实现它:
候选人#1:`std::clone::clone`
我试图添加
#[派生(克隆)]
,但仍然不起作用:

#[派生(克隆)]
发布结构节点{
下一步:选择,
发布值:T
}

我该怎么做

错误的再现:

#[derive(Clone)]
pub struct Node<T> {
    pub next: Option<Box<Node<T>>>,
    pub value: T,
}

fn thing<T>(node: Node<T>) {
    node.clone();
}
另见:


您的代码有许多非惯用方面:

  • 不需要导入的
    std::boxed::Box
  • 不需要的
    展开
    s
  • 不必要的取消引用
这里甚至不需要克隆,使用它可能是不正确的。我会写:

pub fn push_back(&mut self, data: T)
where
    T: Clone,
{
    let spot = match &mut self.head {
        Some(head) => {
            let mut node = &mut head.next;
            while let Some(n) = node {
                node = &mut n.next;
            }
            node
        }
        None => &mut self.head,
    };

    *spot = Some(Box::new(Node::new(data)));
}
另见:


错误的再现:

#[derive(Clone)]
pub struct Node<T> {
    pub next: Option<Box<Node<T>>>,
    pub value: T,
}

fn thing<T>(node: Node<T>) {
    node.clone();
}
另见:


您的代码有许多非惯用方面:

  • 不需要导入的
    std::boxed::Box
  • 不需要的
    展开
    s
  • 不必要的取消引用
这里甚至不需要克隆,使用它可能是不正确的。我会写:

pub fn push_back(&mut self, data: T)
where
    T: Clone,
{
    let spot = match &mut self.head {
        Some(head) => {
            let mut node = &mut head.next;
            while let Some(n) = node {
                node = &mut n.next;
            }
            node
        }
        None => &mut self.head,
    };

    *spot = Some(Box::new(Node::new(data)));
}
另见: