Hello (and a quick question)

I've been programming in other languages for years but I'm relatively new to Rust. I have what I'm sure will turn out to be a noob question, but here goes:

I create a struct, initialize a variable using the struct and I push it to a vec. All is fine until I pop() it out. The variable that captures it no longer sees it as the struct. Instead it sees it as a std::option:Option type. Here's an example:

#![allow(unused)]
struct someStruct 
{
    a: i32,
    b: i32
}

fn main() {
    let aa = someStruct{a:10, b:20};
    let mut vec : Vec<someStruct> = Vec::new();
    vec.push(aa);
    let bb = vec.pop();
    println!("{}",bb.a)
}

The error I get back is as follows:

   Compiling playground v0.0.1 (/playground)
error[E0609]: no field `a` on type `std::option::Option<someStruct>`
  --> src/main.rs:14:22
   |
14 |     println!("{}",bb.a)
   |                

If anyone has any thoughts, I thank you in advance!

Kind regards,
C

What should happen if the Vec is empty? In Rust, we use the Option type to represent the possibility that a value is absent. In this case, you know there is a value, so you could use bb.unwrap().a to access it. You can read the very good Rust book to learn more.

P.S. wrap your code in triple backticks (i.e ``` ) to enable syntax highlighting

edit: whoops, sent before I was ready

3 Likes

Perfect! That was it. Yes, I did just buy a Rust book and I've been using the link you sent. Somehow I never saw this solution. Thank you very much for taking the time.

1 Like