Struct field having a Pointer(reference) to a type

Hi I am new to Rust. I just want to know what is the correct way of have a field in struct to point to another type(could be another struct).
For example here is my code:
st1 uses Box VS st2 uses &

pub struct Mesh<'a> {
    pub st1: Box<Station<'a>>, // STATION IS ANOTHER STRUCT
    pub st2: &'a Station<'a>,
    pub station_list: & 'a Vec<Station<'a>>,
}

impl Mesh<'_> {
    pub fn new() -> Self {
        Self {
            st1: Box::from(Station::new()),
            st2: &Station::new(),
            station_list: &vec![ ],
            mesh_id: MESH_ID.to_owned(),
            wifi_interface: get_wifi_interface().unwrap()
        }
    }
}

this code doesn't compile and I get this error: cannot return value referencing temporary value,
Cause of st2, and station_list. In general I want to learn pointers in rust too.

So the question is:
which way should I go with: the way st1 defined or the way st2 defined OR another recommenced way?

Would you please assis?

Rust gives you several different ways of keeping a "pointer" or "reference" to data stored elsewhere, and you have to choose the pointer type that's best for each individual situation—there's no one-size-fits-all recommendation. The main question when deciding what kind of pointer to use is ownership: some pointer types own the underlying values, like Box<T>, while others represent a temporary borrow of the underlying value, like &T, and still others represent shared ownership of the value, like Rc<T>. Vec<T> is itself an owning pointer type that can store multiple values, so normally you work with Vecs directly instead of wrapped in another pointer (Box<Vec<T>> or &Vec<T>). If you have a good understanding of ownership, the Smart Pointers chapter in The Rust Programming Language has more information about these types and when they're useful.

My general recommendation would be not to use references &T in your own structs until you're more experienced in Rust, because it can make your life difficult and you usually want your struct fields to own data instead of borrowing it. Prefer owning pointers like Vec<T>, String, and Box<T> in struct fields.

2 Likes

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.