I have a String
and want to pass it to this method: soapysdr::Device::new
.
A corresponding toy example would be the following function foo
:
struct Args { /* … */ }
impl<'a> From<&'a str> for Args {
fn from(_value: &'a str) -> Self {
Args { /* …*/ }
}
}
fn foo<A: Into<Args>>(_args: A) {
/* …*/
}
Now lets say we have a String
named s
and we try to pass it with &s
:
fn main() {
let s = String::from("Some string from outside world.");
//foo(&s); // doesn't work
}
This will fail:
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `Args: From<&String>` is not satisfied
--> src/main.rs:15:9
|
15 | foo(&s);
| --- ^^ the trait `From<&String>` is not implemented for `Args`
| |
| required by a bound introduced by this call
|
= note: required for `&String` to implement `Into<Args>`
note: required by a bound in `foo`
--> src/main.rs:9:11
|
9 | fn foo<A: Into<Args>>(_args: A) {
| ^^^^^^^^^^ required by this bound in `foo`
help: consider dereferencing here
|
15 | foo(&*s);
| +
I actually have several options to fix this:
fn main() {
let s = String::from("Some string from outside world.");
//foo(&s); // doesn't work
foo(&s as &str); // where is this syntax described?
foo(&*s); // a bit cryptic when reading the code
foo(<&str>::from(&s)); // I don't really want to allow arbitrary conversions though
}
I'm tempted to use the &s as &str
syntax. But what is that syntax actually? I didn't find this use-case of as
in the reference or in std
(keyword as
). Is it correct and/or idiomatic to use it here? Is this something where the documentation isn't complete, or did I just miss something?
Update: I think I found it. It's actually in the reference (as linked above):
as
can be used to explicitly perform coercions, […]
So I guess it's a coercion here.
The documentation of std
regarding the as
keyword doesn't seem to mention this use-case of as
though.