Struct fields and ownership reassignment

I have a use case where I want to transition from one struct type into another, moving data to the new place. My guess is that no copy should be involved since I just transfer ownership of fields, though I am a little puzzled about how new struct will be able to build it's memory layout without copying?

struct Topic {
    pub name: String,
    pub topic: String
}
#[derive(Debug)]
struct IndexedTopic {
    index: u32,
    name: String,
    topic: String
}
impl Topic {
    pub fn index(self, index: u32) -> IndexedTopic {
        IndexedTopic {
            name: self.name,
            topic: self.topic,
            index
        }
    }
}

fn main() {
    let topic = Topic { name: "foo".to_owned(), topic: "bar".to_owned() };
    dbg!(topic.index(1));
}

You could do this:

struct Topic {
    pub name: String,
    pub topic: String
}

struct IndexedTopic {
    index: u32,
    topic: Topic,
}

so that you don't have to copy the fields manually

Thanks @RustyYato, I actually wanted to understand if in my case compiler will perform memory copy or new struct will be created without copying. I was not able to find answer on this question in the nomicon.

The only way to check that is looking at the assembly :slight_smile:

But copying 6 usizes should almost never be an issue

1 Like

Oh, it just occurred to me that your worried about copying the strings. Moving a String will just copy the pointer and two usizes, not the actual string.

Ah, right!

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