Is it possible to exclude supporting arguments in a common function?

Since the parameter of the type type Tcan be of any type, including a link, I was wondering if it is possible to refuse links in common functions, i.e. write something like:

use std::ops::Deref;

fn foo<T: !Deref>(x: T) -> T {}

This, however, is not allowed and breaks down already at the parsing stage.

I read about optin_builtin_traits, but it only supports rejecting auto-characters, so it will not work because it is Derefnot an automatic sign.

Can this be achieved?

+4
source share
1 answer

Yes, you can use auto-tags for this:

#![feature(optin_builtin_traits)]

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}>`
}

Please note that this also excludes:

  • tagged with a 'statichello call
  • , , iter()

.

, 'static:

fn foo<T: 'static>(x: T) -> T {}
+4

Source: https://habr.com/ru/post/1696321/


All Articles