NeuroWhAI의 잡블로그

[Rust] std::iter::{Iterator, IntoIter} 본문

개발 및 공부/언어

[Rust] std::iter::{Iterator, IntoIter}

NeuroWhAI 2018. 1. 1. 22:28


https://ideone.com/30uZwT


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::fmt;
use std::iter;
 
 
struct LinearFunctionIterator {
    fun: LinearFunction,
    x: i32,
    end: i32,
}
 
impl LinearFunctionIterator {
    fn new(fun: LinearFunction, begin: i32, end: i32-> LinearFunctionIterator {
        LinearFunctionIterator {
            fun: fun,
            x: begin,
            end: end,
        }
    }
}
 
impl iter::Iterator for LinearFunctionIterator {
    type Item = f64;
    
    fn next(&mut self-> Option<Self::Item> {
        if self.x == self.end {
            return None
        }
        
        let result = self.fun.feed(self.x as f64);
        
        if self.x < self.end {
            self.x += 1;
        }
        else {
            self.x -= 1;
        }
        
        return Some(result);
    }
}
 
 
struct LinearFunction {
    a: f64,
    b: f64,
}
 
impl LinearFunction {
    fn new(a: f64, b: f64-> LinearFunction {
        LinearFunction {
            a: a,
            b: b,
        }
    }
 
    fn feed(&self, x: f64-> f64 {
        self.a * x + self.b
    }
}
 
impl fmt::Display for LinearFunction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "f(x) = {} * x + {}"self.a, self.b)
    }
}
 
impl iter::IntoIterator for LinearFunction {
    type Item = f64;
    type IntoIter = LinearFunctionIterator;
    
    fn into_iter(self-> Self::IntoIter {
        LinearFunctionIterator::new(self010)
    }
}
 
 
fn main() {
    let fun = LinearFunction::new(2.01.0);
    println!("{}", fun);
    
    for y in fun.into_iter() {
        println!("{}", y.round());
    }
}
cs

std::fmt::Display는 덤


IntoIter의 단점이라면 into_iter가 self를 받기 때문에 소유권이 넘어가서 한번 호출하면 다시 쓰기 귀찮다는거?




Comments