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.

Post History

60%
+1 −0
Q&A How can I create and modify a struct over iterations of a loop?

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 som...

2 answers  ·  posted 3mo ago by GeraldS‭  ·  last activity 2mo ago by GeraldS‭

#2: Post edited by user avatar GeraldS‭ · 2024-07-29T06:42:59Z (3 months ago)
added additional code for a (somewhat) working example.
  • How can I create and modify variables over iterations of a loop?
  • How can I create and modify a struct over iterations of a loop?
  • 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.
  • ```ini
  • [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:
  • ```php
  • $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](https://doc.rust-lang.org/rust-by-example/std/option.html).
  • 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:
  • ```rust
  • let mut current_section: Option<Section> = None;
  • for line in read_to_string("input.ini").unwrap().lines() {
  • if line.trim().ends_with("]") {
  • let section = Section::new(line);
  • current_section = Some(section);
  • // --------------- this reinitialization might get skipped
  • }
  • else {
  • let item: str = line.unwrap();
  • current_section.unwrap().add_entry(line);
  • // ^^^^^^^^^^^^^^^ -------- `current_section` moved due to this method call, in previous iteration of loop
  • }
  • }
  • ```
  • 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?
  • 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.
  • ```ini
  • [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.
  • <details>
  • <summary>sample pseudocode</summary>
  • ```php
  • $sections = [];
  • $currentSection = null;
  • for line in ini_files {
  • if ($line is sectionheader) {
  • if ($currentSection is array) {
  • $sections[] = $currentSection;
  • }
  • $currentSection = [];
  • }
  • else {
  • $currentSection[] = $line;
  • }
  • }
  • ```
  • </details>
  • 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](https://doc.rust-lang.org/rust-by-example/std/option.html).
  • 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:
  • ```rust
  • 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
  • }
  • }
  • ```
  • <details>
  • <summary>additional file: section.rs</summary>
  • ```rust
  • #[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));
  • }
  • }
  • ```
  • </details>
  • 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?
#1: Initial revision by user avatar GeraldS‭ · 2024-07-28T14:47:02Z (3 months ago)
How can I create and modify variables over iterations of a loop?
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.

```ini
[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:

```php
$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](https://doc.rust-lang.org/rust-by-example/std/option.html).

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:

```rust
let mut current_section: Option<Section> = None;
for line in read_to_string("input.ini").unwrap().lines() {
    if line.trim().ends_with("]") {
        let section = Section::new(line);
        current_section = Some(section);
     // --------------- this reinitialization might get skipped
    }
    else {
        let item: str = line.unwrap();
        current_section.unwrap().add_entry(line);
     // ^^^^^^^^^^^^^^^ -------- `current_section` moved due to this method call, in previous iteration of loop
    }
}
```

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?