简体   繁体   English

指定特征边界时如何指定临时生命周期?

[英]How to specify a temporary lifetime when specifying trait bounds?

I would like to declare a struct that wraps a generic type T like this:我想声明一个包装通用类型T的结构,如下所示:

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?我如何告诉编译器&T可能是一个临时变量,因此任何生命周期都可以?

I don't want to change my struct signature to MyStruct<'a, T> , as that makes the usage more verbose and complicated.我不想将我的结构签名更改为MyStruct<'a, T> ,因为这会使用法更加冗长和复杂。

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操场: https : //play.rust-lang.org/? version = stable & mode = debug & edition = 2018 & gist =864f6c2ad80544adfa7da96cef8eb69c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实现特征时如何明确指定生存期? - How can I explicitly specify a lifetime when implementing a trait? 指定自定义生命周期时,在特征上使用动态多态性的Rust问题 - Issue with Rust using dynamic polymorphism on trait when specifying lifetime on self 如何使用 OR 逻辑指定特征边界 - How can I specify trait bounds with OR logic 如何为创建具有特征生命周期边界的对象的生产者找到通用边界 - How to find generic bounds for producer that creates objects with trait-lifetime bounds Rust - 为借用特征指定生命周期参数 - Rust - Specifying a Lifetime Parameter for the Borrow Trait 在 Iterator trait 中指定关联类型的生命周期 - Specifying lifetime of the associated type in the Iterator trait 如何为涉及对中间局部变量的引用的闭包指定生存期限? - How to specify lifetime bounds for a closure involving references to intermediate local variables? 我如何在 rust 实现中为具有 static 生命周期的特征指定结构生命周期? - How can i specify struct lifetime in rust implementation for trait with static lifetime? 如何为具有生命周期的结构实现“具有静态生命周期的特征”? - How to implement a trait with 'static lifetime for a struct with lifetime 'a? 实现迭代器特征时如何修复生命周期不匹配? - How to fix lifetime mismatch when implementing Iterator Trait?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM