Im wrestling with an interesting problem I found with lifetimes and type specifiers in a struct definition. What I'm trying to do is restrict all fields with type S
- which is defined as Into<Option<&str>>
, so that I can pass either an Option
or str
as a value for the field - to a lifetime 'a
which is defined as the struct's lifetime. I'm using rustc version 1.58.1
in case it helps.
Here's what I got working so far:
#[derive(Debug)]
struct A<S>
where
S: Into<Option<&'static str>>,
{
my_field: S,
}
fn main() {
let obj = A {
my_field: "hello world",
};
println!("{obj:?}");
}
I want to remove the 'static
and restrict it to 'a
. For reference I want to create multiple fields with a type S
. I tried two variants but unable to get it working with either. Hopefully someone is able to shed light on what I'm doing wrong.
Variant #1
#[derive(Debug)]
struct A<'a, S>
where
S: Into<Option<&'a str>>,
{
my_field: S,
}
error:
error[E0392]: parameter `'a` is never used
|
2 | struct A<'a, S>
| ^^ unused parameter
|
= help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData
Variant #2
Trying where for..
as suggested here
#[derive(Debug)]
struct A<S>
where
for<'a> S: Into<Option<&'a str>>,
{
my_field: S,
}
error:
error: implementation of `From` is not general enough
|
10 | let obj = A {
| ^ implementation of `From` is not general enough
|
= note: `Option<&'0 str>` must implement `From<&str>`, for any lifetime `'0`...
= note: ...but it actually implements `From<&'a str>`