2

I would like to declare a struct that wraps a generic type T like this:

use std::ops::Add;
struct MyStruct<T> where T: Add<&T, Output=T> {
    t: T
}

This fails with:

error[E0637]: `&` without an explicit lifetime name cannot be used here
 --> src/lib.rs:3:33
  |
3 | struct MyStruct<T> where T: Add<&T, Output=T> {
  |                                 ^ explicit lifetime name needed here

error[E0310]: the parameter type `T` may not live long enough

How can I tell the compiler that &T may be a temporary variable, and therefore any lifetime is ok?

I don't want to change my struct signature to MyStruct<'a, T>, as that makes the usage more verbose and complicated.

prosc
  • 327
  • 2
  • 5
  • Does this answer your question? [How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function?](https://stackoverflow.com/questions/47996700/how-do-i-bound-a-generic-type-with-a-trait-that-requires-a-lifetime-parameter-if) – trent Mar 19 '20 at 15:37
  • Also read [How to write a trait bound for adding two references of a generic type?](https://stackoverflow.com/questions/34630695/how-to-write-a-trait-bound-for-adding-two-references-of-a-generic-type) and [How do I write the lifetimes for references in a type constraint when one of them is a local reference?](https://stackoverflow.com/questions/44343166/how-do-i-write-the-lifetimes-for-references-in-a-type-constraint-when-one-of-the) – trent Mar 19 '20 at 15:40

1 Answers1

2
use std::ops::Add;
struct MyStruct<T> where T: for <'a> Add<&'a T, Output=T> {
    t: T
}

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=864f6c2ad80544adfa7da96cef8eb69c

MaxV
  • 2,601
  • 3
  • 18
  • 25