Structure initialization quandry

I have a struct that contains a field I can't figure out how to initialize when the struct is created. I can initialize it later, but not when it is initialize instantiated. Its value depends on other fields. At least that is my understanding. Maybe there is a trick?

pub struct Lexer<'input> {                                                      
    reader: &'input mut BufReader<File>,                                        
    scaneol: bool,                                                              
    lineno: u32,                                                                
    chars: Peekable<Chars<'input>>,                                             
    first_column: usize,                                                        
    current_column: usize,                                                      
    needline: bool,                                                             
    linebuffer: String,                                                         
}                                                                               
                                                                                
impl<'input> Lexer<'input> {                                                    
    pub fn new(reader: &mut BufReader<File>) -> Self {                          
        let mut this = Lexer { reader: reader, scaneol: false, lineno: 1,       
                               linebuffer: String::new(),                       
                               chars: ,                                         
                               first_column: 0, current_column: 0,              
                               needline: false };                               
        let status = this.reader.read_line(&mut this.linebuffer).unwrap();      
        this.chars = this.linebuffer.chars().peekable();                        
        this                                                                    
    }                                                                           
}                                                                               

this is a self-referential struct, which is a anti-pattern in rust and you should avoid it. see:

in rust, when a variable (or field of a struct) is borrowed, it cannot be moved, meaning you cannot assign it to another variable or return it from a function.

if self-referential struct is unavoidable, you can use crates like ouroboros so you don't have to write unsafe code yourself.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.