Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on How can I create and modify a struct over iterations of a loop?

Post

How can I create and modify a struct over iterations of a loop?

+1
−0

How can I have a mutable object (for example a vector) that is created inside a loop iteration and needs to be updated in later iterations of said loop?

As a concrete example, consider parsing something similar to an ini file.

[section1]
entry1
entry2

[section2]
entry3
entry4

In a simple scripting language like PHP I would just create an array when a new section starts, append items and store it away when the next section starts.

sample pseudocode
$sections = [];
$currentSection = null;
for line in ini_files {
   if ($line is sectionheader) {
       if ($currentSection is array) {
           $sections[] = $currentSection;
       }
       $currentSection = [];
   }
   else {
       $currentSection[] = $line;
   }
}

Now in Rust it's not that easy of course. If I understood correctly, the $var = null/None and assign as needed schema is done using Options instead.

I'm currently trying to wrap my head around that. Let's say I have the following loop, and Section is a custom struct that is supposed to store the related entries:

let mut sections: Vec<Section> = Vec::new();
let mut current_section: Option<Section> = None;
for line in read_to_string("input.ini").unwrap().lines() {
    if line.trim().ends_with("]") {
        if current_section.is_none() {
            sections.push(current_section.unwrap());
        }
        current_section = Some(Section::new(line));
     // --------------- this reinitialization might get skipped
    }
    else {
        current_section.unwrap().add_entry(line);
     // ^^^^^^^^^^^^^^^ ------- `current_section` moved due to this method call,
     //                         in previous iteration of loop
    }
}
additional file: section.rs
#[derive(Debug)]
pub struct Section {
    pub name: String,
    pub entries: Vec<String>,
}

impl Section {
    pub fn new(name: &str) -> Section {
        Section {
            name: String::from(name),
            entries: Vec::new()
        }
    }

    pub fn add_entry(&mut self, line: &str) {
        self.entries.push(String::from(line));
    }
}

I get that current_section is moved and that I can't access it anymore due to the changed ownership. But how can I store it so that I can access it on further iterations? I tried every combination of referencing and dereferencing with & and * I could think of.

How can I store a variable from a loop iteration and still be able to modify it at later iterations?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

This code doesn't do anything with the `current_section`s, i.e. it doesn't appear to store them in a ... (2 comments)
This code doesn't do anything with the `current_section`s, i.e. it doesn't appear to store them in a ...
Derek Elkins‭ wrote 4 months ago

This code doesn't do anything with the current_sections, i.e. it doesn't appear to store them in a sections array like the pseudo-code. Is that intentional?

GeraldS‭ wrote 4 months ago

It's a simplified example. Currently I'm only interested on how to modify it.