由于泛型类型参数T
可以是任何类型,包括引用,我想知道是否可以选择退出泛型函数中的引用,即能够编写如下内容:
use std::ops::Deref;
fn foo<T: !Deref>(x: T) -> T {}
然而,这是不允许的,并且在解析阶段就已经中断了。
我读到optin_builtin_traits https://github.com/rust-lang/rust/issues/13231,但它只支持选择退出自动特征,所以它也不起作用,因为Deref
不是自动特征。
有可能实现这一目标吗?
是的,您可以为此使用自动特征:
#![feature(auto_traits)]
#![feature(negative_impls)]
auto trait NotReference {}
impl<'a, T> !NotReference for &'a T {}
impl<'a, T> !NotReference for &'a mut T {}
fn no_references<T: NotReference>(_: T) {}
fn main() {
no_references(42); // OK
no_references(&42); // the trait bound `&{integer}: NotReference` is not satisfied
no_references("hello"); // the trait bound `&str: NotReference` is not satisfied
no_references(vec![1, 2, 3]); // OK
let x = vec![1, 2, 3];
no_references(x.iter()); // the trait bound `&{integer}: NotReference` is not satisfied in `std::slice::Iter<'_, {integer}>`
}
请注意,这也排除了:
- 参考文献与
'static
生命周期,如“hello”调用所示
- 任何结构contains也是一个参考,如
iter()
call
我可能会排除一些终生问题。
实际上,这就是'static
绑定的作用是:
fn foo<T: 'static>(x: T) -> T {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)