How to enforce immutability to prevent the modification of values in Rust

1 Answer

0 votes
// Immutable User in Rust (Using Default Immutability and No Mutable Bindings)

//
// Rust enforces immutability by default:
//
// 1. Variables are immutable unless declared with `mut`
// 2. Struct fields cannot be changed unless the entire struct is mutable
// 3. No setters = no mutation
// 4. Ownership rules prevent accidental modification
//
// This makes Rust one of the strongest languages for immutability.
//

// Define an immutable User struct
struct User {
    id: u32,
    name: String,
}

impl User {
    // Constructor
    fn new(id: u32, name: &str) -> User {
        User {
            id,
            name: name.to_string(),
        }
    }

    // Getter methods (read-only)
    fn id(&self) -> u32 {
        self.id
    }

    fn name(&self) -> &str {
        &self.name
    }
}

fn main() {
    // Immutable user (no `mut`)
    let user = User::new(42, "Sophia");

    println!("ID: {}", user.id());
    println!("Name: {}", user.name());

    // These lines will NOT compile if uncommented:
    //
    // user.id = 100;          // cannot assign to field of immutable binding
    // user.name = "Tom".into(); // cannot assign to field of immutable binding
    //
    // Rust prevents mutation at compile time, before the program even runs.

    // Demonstrate that reading is allowed
    let id_copy = user.id();
    let name_copy = user.name();

    println!("ID copy: {}", id_copy);
    println!("Name copy: {}", name_copy);
}



/* 
run:

ID: 42
Name: Sophia
ID copy: 42
Name copy: Sophia

*/

 



answered 7 hours ago by avibootz
...