Post

Rust TryFrom trait

♧ Rust TryFrom trait 관련 링크

# Rust doc 예제 for TryFrom trait

# Rust doc for TryFrom trait


☞ Rust TryFrom trait

  • 특정 타입을 다른 타입으로 변경 시 사용하는 trait이다
    • From trait 의 확장이라고도 할 수 있다.
    • From tarit 과 다른점은 Result를 리턴 한다는 것 → 실패 시, 에러처리가 가능하다.
    • 직접 Error 타입을 설정할 있다.


  • example
    • u8 배열을 Request 구조체로 변경하는 예제이다.
    • 수명과 예외처리에 대해서는 일단 넘어가자.
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
use std::str;

#[derive(Debug)]
pub struct Request<'a> {
    msg : &'a str,
}

impl<'a> TryFrom<&'a [u8]> for Request<'a> {
    type Error = String;

    fn try_from(buf: &'a [u8]) -> Result<Request<'a>, Self::Error> {
        let msg: &str = str::from_utf8(buf).map_err(|e| e.to_string())?;

        Ok(Self {
            msg
        })
    }
}

fn main() {
    let buf:[u8; 3] = [0x31; 3];
    let result = Request::try_from(&buf[..]);

    println!("Output - {:?}", result);
}


결과
Output - Ok(Request { msg: "111" })
This post is licensed under CC BY 4.0 by the author.