When and how to use the link vector

This code compiles correctly. It has some unused code warnings, but right now everything is fine.

use std::collections::BTreeMap; enum Object<'a> { Str(String), Int(i32), Float(f32), Vector(Vec<&'a Object<'a>>), Prim(fn(State) -> State) } struct State<'a> { named: BTreeMap<String, &'a Object<'a>>, stack: Vec<Object<'a>> } impl<'a> State<'a> { fn push_int(&mut self, x: i32) { self.stack.push(Object::Int(x)); } } fn main() { println!("Hello, world!"); let obj = Object::Str("this is a test".to_string()); } 

An important part of this code is push_int and stack: Vec<Object<'a>> .

I'm kind of trying to create a stack-based virtual machine. I want to pass state to functions that can pick things up from the stack, manipulate stuff, and then put some stuff back on the stack; the named field will hold the named objects.

I have a suspicion that it would be better to have a stack represented as Vec<&'a Object<'a>> . As I have now, I am afraid that I will make the mistake of inefficiency. Is my guess right?

The second part of the problem is that I do not know how to make the link version vector work. Creating a new value with the correct lifetimes to push onto the stack does not work for me.

I am a bit vague about this issue, so if I were unclear, ask me questions to clear things up.

+5
source share
1 answer

The reason you cannot make it work is because structures cannot have fields related to other fields. (See Supporting links below.)

What you can do is put all the Object in your Vec , and let the HashMap contain the indices of the named elements that it refers to.

 struct State { named: BTreeMap<String, usize>, stack: Vec<Object> } 

I will also remove all life situations from your example, since this can be done completely with the objects belonging to it.

 enum Object { Str(String), Int(i32), Float(f32), Vector(Vec<Object>), Prim(fn(State) -> State) } 

You can try the working implementation in the Playground

Supporting links:

+6
source

Source: https://habr.com/ru/post/1235495/


All Articles