A lifetime annotation problem

I have two structs:

struct MyStruct1<'a, T> {
    data: &'a T,
}

struct MyStruct2<T> {
    data: T,
}

Can I make the two structs into one, like:

struct MyStruct<'a, T> {
    data<'a>: T
}

So I can:

let a_vec = vec![1i32, 2, 3];

let my_struct1 = MyStruct { data: a_vec };
let my_struct2 = MyStruct { data: &a_vec }; 

A bare type parameter T also covers references (because it doesn't constrain the type in any particular way), so MyStruct2 suffices in itself.

2 Likes

Thanks very much.
One more asking: If I use MyStruct2, how can I define a funciton as following:

fn get_part<T, N>(my_struct2: &MyStruct2<T>) -> Vec<N>
//T maybe a Vec<N> or a &Vec<N>, so the function can return Vec<N>
where 
    N: Clone
    T: A Trait  that can be indexed in, and the element is type N
{
    my_struct2.data[..10].to_vec()
}

Something like T: AsRef<[N]> could work for your use-case.

1 Like