DEV Community

Cover image for What This Senior Developer Learned From His First Big Rust Project

What This Senior Developer Learned From His First Big Rust Project

Andrew (he/him) on January 09, 2024

cover photo by Pixabay Here is a bit of background on me according to my company's org chart on Workday, my current title is "Senior Consul...
Collapse
 
gsnoff profile image
Ilyas Gasanov • Edited

You can also use S: AsRef<str> (or s: impl AsRef<str>) if you don’t need the String ownership within the function code. It’s just as common and ergonomic, and it saves on performance too. The only downside is that it doesn’t support Display/ToString types which don’t contain immediate string data.

Ideally, it should’ve been possible to define a custom trait with a function which returns a Cow<'a, str>, and provide blanket implementations for all types that a) implement AsRef<str> (returning Cow::Borrowed(str)), and b) implement Into<String> but do not implement AsRef<str> (returning Cow::Owned(String)). Alas, Rust currently doesn’t support custom generic specializations or non-union trait/type guard operators, since it’s a huge headache to do such features in a sound way, so that they cannot break SemVer guarantees after landing.

Collapse
 
awwsmm profile image
Andrew (he/him)

What's the benefit to using s: impl AsRef<str> over s: &str?

I asked myself the above and then found this message board thread from 2016: users.rust-lang.org/t/idiomatic-st...

...seems this is not a new discussion we're having.