Как клонировать Box <CustomStruct>, когда я получаю "метод с именем clone"? - PullRequest
0 голосов
/ 14 июня 2019

Я хочу клонировать head, что Box<Node<T>>:

let mut node = Some((*head).clone());

Вот полный код ( детская площадка ):

use std::boxed::Box;

pub struct List<T> {
    pub head: Option<Box<Node<T>>>,
    pub size: u64,
}

impl<T> List<T> {
    pub fn new() -> List<T> {
        return List {
            head: Option::None,
            size: 0,
        };
    }

    pub fn push_back(&mut self, data: T) {
        match &self.head {
            Some(head) => {
                let mut node = Some((*head).clone());
                while (*(node).unwrap()).next.is_some() {
                    node = (*node.unwrap()).next;
                }
                node.unwrap().next = Some(Box::new(Node::new(data)));
            }
            None => {
                self.head = Some(Box::new(Node::new(data)));
            }
        }
    }
}

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

impl<T> Node<T> {
    pub fn new(v: T) -> Node<T> {
        Node {
            next: Option::None,
            value: v,
        }
    }
}

Компилятор продолжает утверждать, что метод clone существует, но следующие границы признаков не были выполнены:

error[E0599]: no method named `clone` found for type `std::boxed::Box<Node<T>>` in the current scope
  --> src/lib.rs:19:45
   |
19 |                 let mut node = Some((*head).clone());
   |                                             ^^^^^
   |
   = note: the method `clone` exists but the following trait bounds were not satisfied:
           `Node<T> : std::clone::Clone`
           `std::boxed::Box<Node<T>> : std::clone::Clone`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `clone`, perhaps you need to implement it:
           candidate #1: `std::clone::Clone`

Я пытался добавить #[derive(Clone)], но он все еще не работает:

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

Как я могу это сделать?

1 Ответ

1 голос
/ 14 июня 2019

Воспроизведение ошибки:

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

fn thing<T>(node: Node<T>) {
    node.clone();
}
error[E0599]: no method named `clone` found for type `Node<T>` in the current scope
 --> src/lib.rs:8:10
  |
2 | pub struct Node<T> {
  | ------------------ method `clone` not found for this
...
8 |     node.clone();
  |          ^^^^^
  |
  = note: the method `clone` exists but the following trait bounds were not satisfied:
          `Node<T> : std::clone::Clone`
  = help: items from traits can only be used if the trait is implemented and in scope
  = note: the following trait defines an item `clone`, perhaps you need to implement it:
          candidate #1: `std::clone::Clone`

Вам необходимо добавить границу черты, которая говорит, что T реализует Clone:

fn thing<T>(node: Node<T>)
where
    T: Clone,
{
    node.clone();
}

Смотри также:


Ваш код имеет множество неидиоматических аспектов:

  • ненужный импорт std::boxed::Box
  • ненужно unwrap с
  • ненужные разыменования.

Вам даже не нужен клон здесь, и, вероятно, использовать его некорректно. Я бы написал:

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)));
}

Смотри также:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...