[在指定特征界限时如何指定临时寿命?

问题描述 投票:0回答:1

我想声明一个包装如下通用类型T的结构:

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

此操作失败:

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

我如何告诉编译器&T可能是一个临时变量,因此任何生存期都可以吗?

我不想将我的结构签名更改为MyStruct<'a, T>,因为这会使用法更加冗长和复杂。

rust traits lifetime
1个回答
0
投票
use std::ops::Add;
struct MyStruct<T> where T: for <'a> Add<&'a T, Output=T> {
    t: T
}

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

© www.soinside.com 2019 - 2024. All rights reserved.