In the context of converting a infix expression to a postfix one, using the Shunting-yard algorithm. I want to use a vector to store the output, which would store both operator and numeric type data.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Operator {
Add,
Sub,
Mul,
Div,
}
fn main() {
let mut output: Vec<String> = Vec::new(); // create an output vector
let a = 2;
let b = Operator::Add;
let c = 3;
output.push(a.to_string());
output.push(b.to_string());
output.push(c.to_string());
}
This above code of course doesn't compile, since the to_string()
method is not defined for Operator
. I see two ways to fix it:
to_string()
methodOperator
. I think the second is the preferred choice, though I don't know if creating a vector of references will introduce lots of complexity.
Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O (1) indexing and push and pop operations in vector also take O (1) complexity.
Arrays and vectors being one of the first few data structures that new programmers learn, it is no surprise that Rust too has a solid support for them. But as we saw, Rust's safety guarantees do not allow programmers to abuse these fundamental data types.
Arrays are one of the first data types beginner programmers learn. An array is a collection of elements of the same type allocated in a contiguous memory block. For example, if you allocate an array like this: Then all the i32 integers are allocated next to each other on the stack: In Rust, an array's size is part of the type.
On the other hand, slices are read-only objects. To get a slice, use &. Example: In Rust, it’s more common to pass slices as arguments rather than vectors when you just want to provide read access. The same goes for String and &str. The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector.
There's no need to use references; just store the numbers and Operator
s directly in an enum:
enum Thing {
Op(Operator),
Number(i32),
}
fn main() {
let mut output: Vec<Thing> = Vec::new();
let a = 2;
let b = Operator::Add;
let c = 3;
output.push(Thing::Number(a));
output.push(Thing::Op(b));
output.push(Thing::Number(c));
}
And then match
on them when taking them out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With