Return immutable string in Rust

I'm looking to return a string from a function in Rust, but the only option I see right now is return String

, which can be changed. While this is incorrect, I really like the idea of ​​returning some strings, such as error descriptions, as immutable.

So, is there a way for functions to return, for example Result<Something, String>

, to actually return the error as immutable? Is it possible to enforce it on the type itself while still returning something Str

-compatible? Or should I just stop worrying and always give String

s? (like most functions std::io



source to share

1 answer

Rust uses the concept of inherited mutability, that is, whether a given piece of data has changed or not, the owner of that work. Hence, if your piece of data is a regular structure, for example String

, you cannot influence its mutability after returning it.

However, there is some workaround. Since Rust is a value-based language, an instance of a struct with a single field of some type has exactly the same representation as just a value of that type, so you can create a wrapper for your type that doesn't expose its field directly, but provides a getter. which returns an immutable reference to that field:

struct ImmutableString(String);

impl ImmutableString {
    fn get_ref(&self) -> &String { &self.0 }

    // or, even better:

    fn as_slice(&self) -> &str { self.0.as_slice() }


Due to compiler optimizations, this is a zero-cost wrapper and both methods are deferred, but since these methods are the only way to interact with structural internals and they only return immutable references, the value of such a structure will effectively be immutable.

However, I would say that you really don't need all of this. The concept of ownership and borrowing rust removes all of the problems that you usually face with mutable data in languages ​​like C or C ++ or Java, so just be natural - if you return String

, you relinquish your control over it so that the caller the subscriber decided what they want to do with him, there are no restrictions.



All Articles