amarao: (Default)
[personal profile] amarao
!markdown

А вот я и дошёл до странной проблемы, которую я не могу понять.

#[derive (Debug)]
struct Count{
from: u32,
to: u32
}

#[derive (Debug)]
struct CountIterator<'a>{
params: &'a Count,
cur: u32
}

impl Count{
pub fn new(from: u32, to: u32) -> Self {
Count{from, to}
}
}

impl<'a> Iterator for CountIterator<'a>{
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.cur < self.params.to{
self.cur += 1;
Some(self.cur)
}else{
None
}
}
}

impl<'a> IntoIterator for Count{
type Item = u32;
type IntoIter = CountIterator<'a>;
fn into_iter(&'a self) -> Self::IntoIter {
CountIterator{params: self, cur: self.from}
}

}

И этот код неправильный, потому что

    222 | impl<'a> IntoIterator for Count{
        |      ^^ unconstrained lifetime parameter

И я не понимаю, почему так. И оно неприятно щекочет где-то в районе type parameters, потому что редактор подсказывает, что на месте IntoIter = надо писать
type IntoIter: Iterator<Item = Self::Item> = .....;

И я ни черта не понимаю в написанном. Либо это RLS фигню пишет, либо я что-то глубоко не понимаю. Иду пересматривать про итераторы. Что-то я упускаю...

Date: 2022-12-28 04:47 pm (UTC)
From: [personal profile] cyberursus

Вроде в описании ошибки довольно подробно все расписано: https://doc.rust-lang.org/error_codes/E0207.html

Там, собственно, есди посмотреть сигнатуру IntoIterator::into_iter(self), которая принимает self, а не &self, который ты назад в виде ссылки не вернешь (метод его сожрал) то понятно, откуда брать лайфтайм - надо IntoIterator для ссылки реализовать:

impl<'a> IntoIterator for &'a Count{
    type Item = u32;
    type IntoIter = CountIterator<'a>;
    fn into_iter(self) -> Self::IntoIter {
        CountIterator{params: self, cur: self.from}
    }
}

Оно как-бы немного некрасиво в использовании будет, но в принципе - ок:

for i in &Count::new(0, 10) {
    println!("i: {}", i);
}

Естественно, можно что-то типа такого сделать:

struct CountIterator{
    params: Count,
    cur: u32
}

impl<'a> IntoIterator for &'a Count{
    type Item = u32;
    type IntoIter = CountRefIterator<'a>;
    fn into_iter(self) -> Self::IntoIter {
        CountRefIterator {params: self, cur: self.from}
    }
}

impl IntoIterator for Count{
    type Item = u32;
    type IntoIter = CountIterator;
    fn into_iter(self) -> Self::IntoIter {
        let cur = self.from;
        CountIterator {params: self, cur}
    }
}

Profile

amarao: (Default)
amarao

February 2026

S M T W T F S
123456 7
8910111213 14
15161718192021
22232425262728

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Feb. 25th, 2026 03:47 pm
Powered by Dreamwidth Studios