How is the new()method implemented?

Hello,

I want to build a small VM but am unable to write a correct new() method. The field code is from a module in the same crate, common:CodeChunk. I get 6 errors: the 1st and 3rd expected one of ,, :, or } is for the :: between common and CodeChunk and :: between Vec and new, the 2nd 4th and 6th are expected identifier for all fields that are primitive Datatype

pub struct VM {
	code: common::CodeChunk,
	IP:usize,
	stack:Vec<i32>,
	max_stack_size: usize,
	SP:usize
}

impl VM {
	pub fn new() -> Self {
		Self{common::CodeChunk::new(), 0, Vec::new(),256,256}
	}
...
}

You have to specify the field names when instantiating a struct.

3 Likes

Note that new is not special - it's only a convention, at the language's level it's simply another associated function, nothing more.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.