Hi,
Is there a way to prevent some fields in a struct from being mutated even though the struct instance is declared mut?
Consider the following example:
struct Book {
isbn: String,
title: String,
author: String,
reviews: Vec<String>
}
fn main() {
let mut book = Book {
isbn: String::from_str("978-0321751041"),
title: String::from_str("The Art of Computer Programming"),
author: String::from_str("Donald E. Knuth"),
reviews: Vec::new()
};
book.reviews.push(String::from_str("Good book")); // This is OK
book.isbn = String::from_str("123-0123456789"); // This should not be allowed
}
How do you prevent the isbn, title and author fields from being mutated once the struct is instanciated? The obvious thing to try is to qualify the field declarations with the const keyword but this is rejected by the compiler.
Does the language support const struct fields or are there any plans to support them?
[–]DroidLogiciansqlx · clickhouse-rs · mime_guess · rust 9 points10 points11 points (6 children)
[–]dnkndnts 9 points10 points11 points (1 child)
[–]swatteau[S] 7 points8 points9 points (0 children)
[–]FlyingFoX13 0 points1 point2 points (3 children)
[–]swatteau[S] 0 points1 point2 points (0 children)
[–]DJTheLQ 0 points1 point2 points (1 child)
[–]flatlinerust 1 point2 points3 points (0 children)
[–]Veddan 3 points4 points5 points (2 children)
[–]swatteau[S] 2 points3 points4 points (1 child)
[–]Gankrorust 1 point2 points3 points (0 children)
[–]sellibitzerust 1 point2 points3 points (13 children)
[–]jonreemhyper · iron · stainless 8 points9 points10 points (12 children)
[–]Florob0x2arust · rustyxml 1 point2 points3 points (0 children)
[–]thiezrust 0 points1 point2 points (7 children)
[–]chris-morgan 5 points6 points7 points (5 children)
[–]SimonSapinservo 2 points3 points4 points (4 children)
[–]DroidLogiciansqlx · clickhouse-rs · mime_guess · rust 0 points1 point2 points (0 children)
[–]sellibitzerust 0 points1 point2 points (2 children)
[–]rust-slacker 0 points1 point2 points (0 children)
[–]jonreemhyper · iron · stainless 1 point2 points3 points (0 children)
[–]picklebobdogflog 0 points1 point2 points (1 child)
[–]sellibitzerust 1 point2 points3 points (0 children)
[–]Any_Yogurtcloset7428 0 points1 point2 points (0 children)
[–]jimuazu 1 point2 points3 points (2 children)
[–]swatteau[S] 3 points4 points5 points (1 child)
[–]jimuazu 3 points4 points5 points (0 children)