Using an "&str" field inside of a Struct

Hey there, I'm Jose new to the forum and new to Rust as well. I've been studying the language for 1 week, and there are so many things to grasp. I'm getting the hang of it though, in part due to my previous programming background in C#.

I was reading the Struct chapter in the Official Rust Book. In the "Ownership of Struct Data" subsection (Defining and Instantiating Structs - The Rust Programming Language) we are told that it's not possible to use fields that not owned by the Struct type itself, which is logical.

But I was wondering, where I would want to do such a thing. In other words, where should I prefer this:

struct Aircraft<'a> {
fuel: f64,
commander: &'a str,
}

Over this:

struct Aircraft {
fuel: f64,
commander: String,
}

I can't think of a scenario where new "aircraft" types won't own their commander field (following my previous example).

Thank you, hopefully I will get better and better with the language (even if have some troubles finding good step-by-step tutorials).

Cheers!

The are indeed not very common. One example where you might want to do this is if you were implementing the SplitWhitespace iterator, which returns slices into the original string.

struct SplitWhitespace<'a> {
    remaining: &'a str,
}
impl<'a> Iterator for SplitWhitespace<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<&'a str> {
        ...
    }
}

You might like this video, which goes through an example like this.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.