Struct with size + data fields

Is there an idiomatic way to instantiate a

use std::fs::File;
use std::path::Path;
use std::io::Read;

struct SomeStruct {
   data: [u8; 1024],
   size: usize,
}

impl SomeStruct {
    fn from_file(path: &Path) -> Result<SomeStruct, std::io::Error> {
        let mut file = File::open(path)?;
        
        let mut buf: [u8; 1024] = [0; 1024];
        
        let val = SomeStruct {
           data: [0; 1024],
           size: file.read(&mut <this_struct>.data)?,
        };
        
        Ok(val)
    }
}

somehow?

Specifically I mean to initialize the struct without needing to create it first, and then mutably change it's data value. Any way to access the <this_struct>?

No, not until the struct is fully initialized.

If you're happy using that temporary buf, then you can just initialize the fields out of order:

let val = SomeStruct {
    size: file.read(&mut buf)?,
    data: buf,
};

Or you could mutate the size afterward:

let mut val = SomeStruct { data: [0; 1024], size: 0 };
val.size = file.read(&mut val.data)?;

This is why I use field name puns almost exclusively.

impl SomeStruct {
    fn from_file(path: &Path) -> Result<SomeStruct, std::io::Error> {
        let mut file = File::open(path)?;
        
        let mut data: [u8; 1024] = [0; 1024];
        let size = file.read(&mut data)?;
        Ok(SomeStruct { data, size })
    }
}
2 Likes

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