Field that can be String or &'static str

Hello,

I would like to have a struct that can wrap a String or a &'static str. Is there a trait bound that can achieve this?

struct StringWrapper<S: ???> {
  string: S
}

I don't need to mutate, but I'd like String("Hello") and "Hello" to compare equal. Thanks!

Best, Oliver

Is there a trait bound that can achieve this?

A trait bound that will work for this purpose is Borrow<str>.

I don't need to mutate, but I'd like String("Hello") and "Hello" to compare equal.

You will need to write your own PartialEq impl to achieve that:

use std::borrow::Borrow;

struct StringWrapper<S: Borrow<str>> {
  string: S
}

impl<A, B> PartialEq<StringWrapper<B>> for StringWrapper<A>
where
    A: Borrow<str>,
    B: Borrow<str>,
{
    fn eq(&self, other: &StringWrapper<B>) -> bool {
        self.string.borrow() == other.string.borrow()
    }
}

However, if you don't need the choice of string type to be generic/compile-time, then you
can use std::borrow::Cow<'static, str> to get all of the properties you've asked for. This is an enum which stores either a &'static str or a String, and it already has the PartialEq behavior you want, as well as many other useful trait implementations.

use std::borrow::Cow;

struct StringWrapper {
  string: Cow<'static, str>
}
5 Likes

Great, thanks, both might work!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.