NeuroWhAI의 잡블로그

[Rust] 연관된 타입(Associated Types) 본문

개발 및 공부/언어

[Rust] 연관된 타입(Associated Types)

NeuroWhAI 2018. 1. 3. 18:45



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
trait Foo {
    type T: std::fmt::Display; // 연관 타입 선언
    
    fn set(&mut self, data: &Self::T);
    fn get(&self-> &Self::T;
}
 
struct Bar {
    data: i32,
}
 
impl Foo for Bar {
    type T = i32// 연관 타입 정의
    
    fn set(&mut self, data: &Self::T) {
        self.data = *data;
    }
    
    fn get(&self-> &Self::T {
        &self.data
    }
}
 
// Foo를 구현한 녀석의 참조를 받을건데 Foo의 T는 i32로 정의한 녀석만.
fn test(foo: &Foo<T=i32>) {
    println!("{}", foo.get());
}
 
fn main()
{
    let mut bar = Bar { data: 1998 };
    
    test(&bar);
    
    bar.set(&42);
    
    test(&bar);
}
cs

설명은 주석을 참고하시옵소서..

'개발 및 공부 > 언어' 카테고리의 다른 글

[Rust] std::ops::Deref  (0) 2018.01.03
[Rust] std::borrow::Cow  (0) 2018.01.03
[Rust] std::iter::IntoIterator  (0) 2018.01.03
[Rust] 빌드 스크립트  (0) 2018.01.02
[Rust] Youtube playlist를 mp3 파일들로 다운로드  (0) 2018.01.02


Comments