declared. But not mutable by default when passed as argument to some function?
String literals are immutable in many programming languages. When you declare a string literal, it's not mutable by default; it's actually immutable. When you pass a string to a function, the immutability remains. If it seems mutable in some contexts, it's because many languages allow syntactic sugar to make strings appear mutable, or they provide mutable versions of string-like data structures. However, when passed as an argument, the function receives a reference or copy of the string, not the original string itself, preserving immutability.
For example, in main function s is not mutable, but I can pass it to the make_awesome function which needs mut String. fn main() { let s = String::from("Rust"); let s = make_awesome(s); println!("{s}") } fn make_awesome(mut s: String) -> String { s.push_str(" is awesome!"); return s }
well, here you _move_ your string completely (i.e. give up on it completely), and make_awesome can do anything with it, including mutating it
Then isn't it redundant to put mut in function argument (in this case)? Since it is anyway taking ownership?
if you don't mark it as mutable, you won't be able to mutate it
Обсуждают сегодня