Python equivalent class attribute and method

Hi,
what are in rust the python equivalent for class attribute and class method ? where to write static method ?

Rust's equivalent of a "class method" or "static method" is an "associated function", which looks like a method except that it doesn't take a self argument:

struct Record;

impl Record {
    fn delete_all() {
        // ...
    }
}

To call an associated method, prefix it with the type name:

Record::delete_all();

You can also have associated constants:

impl Record {
    const MAX_COUNT: usize = 1024;
}

which can be accessed a similar way: Record::MAX_COUNT.

hi mbrubeck, how to keep count of Record_instances, to avoid to exceed MAX_COUNT in new() constructor ?
to avoid to delete instances if Vec lenght < MIN_COUNT ?

If you want this to be a global count for your whole program, then you could use a static variable. It will need to use locks or atomic operations to prevent data races between threads. You can make it private to a module to hide it from outside code. For example:

pub mod record {
    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
    
    static COUNT: AtomicUsize = AtomicUsize::new(0);
    const MAX_COUNT: usize = 1024;

    pub struct Record;
    
    impl Record {
        pub fn new() -> Result<Record, ()> {
            if COUNT.load(SeqCst) >= MAX_COUNT {
                return Err(())
            }
            COUNT.fetch_add(1, SeqCst);
            Ok(Record)
        }
    }
}

Crates like once_cell and lazy_static have convenient ways to make statics that contain more complicated types, including mutexes.

Or, instead of a global, you could have an object that is responsible for creating Records, and keeping track of the count:

pub struct RecordHolder {
    count: usize,
}

impl RecordHolder {
    const MAX_COUNT: usize = 1024;
    
    pub fn new() -> Self {
        RecordHolder { count: 0 }
    }
    
    pub fn new_record(&mut self) -> Result<Record, ()> {
        if self.count >= Self::MAX_COUNT {
            return Err(());
        }
        self.count += 1;
        Ok(Record)
    }
}
2 Likes

thx!

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.