How to impl all string methods on tuple struct to call this methods directly without unpacking the value?

I have a tuple struct:

#[derive(Debug, Default, Clone)]
pub struct TerminatedString(pub String);

and I want it to behave like a string without unpacking:

let TerminatedString(text) = terminated_string;
text.trim_matches(0);

could somebody explain, how to impl all string methods on this struct, so I can call them directly ?

let terminated_string = TerminatedString::from("test string");
terminated_string.trim_matches(0);

You cannot, not at least in the sense you are thinking about, without manually forwarding each method.
However, you can make it such that a TerminatedString can be borrowed (shared or exclusively) as a String. For this there are two traits: Deref and DerefMut. These allow your type to be borrowed as another type.
In fact, if you look at the docs of String, you'll see that it has a Deref impl for str, meaning that many of the String-methods are actually defined on str and they are available on a String because of the Deref-impl. These are documented here.

2 Likes

Thank you, I like this solution.