Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector store mixed types of data in Rust [duplicate]

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:

  1. Define a to_string() method
  2. Create a vector to store references to numbers and Operator.

I think the second is the preferred choice, though I don't know if creating a vector of references will introduce lots of complexity.

like image 581
enaJ Avatar asked Nov 12 '16 05:11

enaJ


People also ask

What is the use of vector in rust?

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.

Is rust safe for arrays and vectors?

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.

What are arrays in rust?

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.

What is the difference between a vector and a slice in rust?

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.


1 Answers

There's no need to use references; just store the numbers and Operators 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.

like image 124
Chris Emerson Avatar answered Oct 31 '22 00:10

Chris Emerson