0

I am designing a simple struct which groups multiple pieces of owned data together. Once the data is inside the struct, I don't want to expose it to mutation. One of the fields of this struct is a String, I am unsure how I want to expose it through its getter function.

The two ways that jump to mind of doing this are as follows:

struct Foo {
    bar: String,
}

impl Foo {
    // Option 1
    fn bar(&self) -> &String { ... }
    // Option 2
    fn bar(&self) -> &str { ... }
}

I am not sure what the cleanest way to design this would be in Rust. Which is better in a general case? What do the two options conceptually represent to a user of the API?

Llew Vallis
  • 25
  • 1
  • 5
  • 1
    The usual way is to return a `&str`, but it doesn't really matter much. The situation is different when _accepting_ immutable string references rather than returning them. In that case, you should generally [prefer `&str` over `&String`](https://stackoverflow.com/q/40006219). – Sven Marnach Aug 25 '19 at 13:56
  • 1
    @SvenMarnach oh but it does matter! Returning `&String` over `&str` has no advantage for most use cases (unless you really care about being able to access the string's capacity), but returning `&str` now would allow him to change the implementation internally in the future to use something other than `String` without changing a public interface. – mcarton Aug 25 '19 at 21:04
  • @mcarton True, there are a few reasons to use`&str` as the return type. Other reasons are that `&str` is more convenient for matching against string literals, and that it sometimes interacts better with type inference for generics. But overall that's all corner cases in practice. – Sven Marnach Aug 26 '19 at 07:08
  • You can not return reference to String because this will be a dangling pointer: fn bar(&self) -> &String – snnsnn Sep 11 '19 at 18:55

0 Answers0