Похожие чаты

Hi, why is a String literal mutable by default when

declared. But not mutable by default when passed as argument to some function?

5 ответов

16 просмотров

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.

Sudeep- Автор вопроса
Vladisλav
String literals are immutable in many programming ...

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 }

Sudeep
For example, in main function s is not mutable, bu...

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

Sudeep- Автор вопроса
Artem Starikov
well, here you _move_ your string completely (i.e....

Then isn't it redundant to put mut in function argument (in this case)? Since it is anyway taking ownership?

Sudeep
Then isn't it redundant to put mut in function arg...

if you don't mark it as mutable, you won't be able to mutate it

Похожие вопросы

Карта сайта