Heya,
Just started learning Rust, and writing some basic programs with it. When (or how often) do you use AsRef<T>
over &T
?
For example, today I've been writing a trait for a struct that appends strings to itself (in some internal buffer), but I wasn't sure which one to use:
pub trait SomeTrait {
fn append_0(&mut self, name: &str);
fn append_1<TString>(&mut self, name: TString) where TString: AsRef<str>;
}
The first option means any std::string::String
s would need to be passed in as &name
, and after doing in all call sites (and for functions with multiple parameters), the callers were mixed with & and non-&s. It looked unergonomic with &
symbols literred everywhere. On the other hand, using the second option cleaned up how it looked, but then I wasn't sure if that was idiomatic Rust, and it's kind of pervasive where every function would need to have AsRef
(if we're just using a parameter solely within the lifetime of that function).
So I want to ask, what do you do, and what's idiomatic? When should we be using AsRef
, but also, when shouldn't we be using AsRef
?
On a related note, what about Into
?
I've read the entire Rust book, Nomicon and Rust by Example, but none of those give any guidance or explanation about situations these should be used.
Thanks so much.