yes, AsRef<...> is useful for function arguments, so that either a str or a String can be passed without conversion at the call site (usually you'd use it with parameterization: fn func<T: AsRef<str>>(s: T), not with dyn)
but it's not clear to me what you are trying to do by returning a dyn AsRef<...>, instead of a concrete String ?
Ohh... I see what I'm doing wrong now... AsRef is the trait, I'm asking for a trait object (dyn AsRef) when I should be asking for a type that implements the trait (T: AsRef).
fn foo<T: AsRef<str>>(s: T) -> &str { ... }
Still a little confused though.
The clue was that it was asking for dyn, this isn't needed when specifying trait bounds (I think?)
Thanks - I think I was wanting to return either a &str or a String... which I'm now realising is deliberately not allowed? Or maybe just a bad idea in general.
This was with others' implementing the trait in mind, so that they could write an implementation for &str or String as they saw fit.
Not sure if this is applicable to your scenario, but for future reference - when you want to abstract over a piece of data that may be owned or borrowed (or may transition from one to the other), std::borrow::Cow is your friend
This was with others' implementing the trait in mind, so that they could write an implementation for &str or String as they saw fit.
Cow is a good suggestion in the sense that it wraps either a borrowed reference or owned object, but it's meant as an optimization to avoid unnecessary copies, for example in parsers
you need to explicitly manage them, though, which can result in needing more boilerplate code
so i'm not sure it's what you're looking for here as a convenience feature for trait implementers
edit: which makes me wonder how to use Cow with AsRef, the following passthrough function doesn't compilie (cannot return value referencing function parameter input):
the pass-through is an absurd example in the first place , in practice it'd at least check the input string (say, "is it uppercase") and conditionally either return a reference to that, or return a changed owned string
but i can't get it to work with AsRef and lifetimes