What does impl mean when used as an argument type or function return type?

I read this code :

pub fn up_to(limit: u64) -> impl Generator<Yield = u64, Return = u64> {
    move || {
        for x in 0..limit {
             yield x;
        }
        return limit;
    }
}

What does it mean impl? How can this be implemented in plain Rust or C ++?

+5
source share
2 answers

This is a new syntax impl Traitthat allows the programmer to avoid naming generic types. Feature available with Rust 1.26 .

Here it is used in the return position to say that "the return type will implement this trait, and that’s all I’m telling you." In this case, note that all returned function paths must return the same specific type.

, , .

:

+6

What does impl mean?

, impl X " X". , , , UpToImpl , Box<Generator>. , . , , , .

Rust C++?

, up_to, , , Generator:

#![feature(generator_trait)]
use std::{
    ops::{Generator, GeneratorState},
    pin::Pin,
};

pub struct UpToImpl {
    limit: u64,
    x: u64,
}

impl Generator for UpToImpl {
    type Yield = u64;
    type Return = u64;

    fn resume(mut self: Pin<&mut Self>) -> GeneratorState<u64, u64> {
        let x = self.x;
        if x < self.limit {
            self.x += 1;
            GeneratorState::Yielded(x)
        } else {
            GeneratorState::Complete(self.limit)
        }
    }
}

pub fn up_to(limit: u64) -> UpToImpl {
    UpToImpl { x: 0, limit }
}

fn main() {
    let mut v = Box::pin(up_to(3));
    println!("{:?}", v.as_mut().resume());
    println!("{:?}", v.as_mut().resume());
    println!("{:?}", v.as_mut().resume());
    println!("{:?}", v.as_mut().resume());
}

, , , Rust , , yield, , , UpToImpl, . (, , Fn.)

impl Generator . UpToImpl , , . , :

let x: UpToImpl = up_to(10);

, UpToImpl - .

up_to , , impl Generator, , impl trait , . , , , , .

:

+3

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


All Articles