1

Trying to learn Rust by writing a parser, but this error is killing me:

ast.rs(7, 11): this trait cannot be made into an object...
ast.rs(7, 29): ...because it requires `Self: Sized`
ast.rs(16, 5): the trait `ast::ast::Statement` cannot be made into an object

Here's the code:

use crate::token::token;

pub trait Node {
    fn token_literal(&mut self) -> String;
}

pub trait Statement: Node + Clone {
    fn statement_node(&mut self);
}

pub trait Expression: Node + Clone {
    fn expression_node(&mut self);
}

pub struct Program {
    pub statements: Vec<Box<dyn Statement>>,
}

And I'd like to know why does it keep complaining me about the Sized trait, I'm using Box to avoid it and lifetimes?

I do not want to use Generics for the Program struct like

pub struct Program<T: Statement> {
    pub statements: Vec<T>
}

because when I return a Program from a function it complains me about some kind of an error like "it requires 1 argument but got 0"

E_net4
  • 27,810
  • 13
  • 101
  • 139
Skai
  • 31
  • 1
  • 10
  • @E_net4isdownhausted So you're saying that the `Box` gets invalid because of the clone trait? But why? I suppose that when we clone a Box, we clone the pointer itself which doesn't even satisfy my needs but enough to make compiler not complain. Isn't Box a type of a pointer? – Skai Jun 07 '20 at 15:51
  • 1
    _"I suppose that when we clone a Box, we clone the pointer itself"_ That is incorrect, a `Box` provides unique ownership over the pointed value, so even cloning requires the owned value to be cloneable. To attain shared ownership, one would instead use reference-counted smart pointers: `Rc` or `Arc`. – E_net4 Jun 07 '20 at 16:27
  • @E_net4isdownhausted But using `Vec>`, instead of `Vec>` didn't solve the issue either. And I understood that if I use the reference-counted pointers to clone an unsized object, it'll clone the reference, not the value am I right? – Skai Jun 07 '20 at 17:32
  • That is true. Please try the solution in the duplicate target. – E_net4 Jun 07 '20 at 18:42

1 Answers1

-1

The issue is that Clone requires Sized: https://doc.rust-lang.org/src/core/clone.rs.html#108-110.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45