Rust From与into

函数方法:【标准库】

示例:

use std::convert::From;

#[derive(Debug)]
struct Number{
    value:i32,
}

impl From<i32> for Number{
    fn from(item:i32) -> Self{
        Number{
            value:item
        }
    }
}


fn main() {
    let num = Number::from(32);             // 函数类似于String::from()(String 转成 &str)
    println!("My Number-num is = {:?}", num);


    let int_0 = 6;
    let num2:Number = int_0.into();        // 函数类似于to_string(&str 转成 String)
    println!("My Number-num2 is = {:?}", num2);


    let my_str = "hello";
    let my_string = String::from(my_str);
}
// My Number-num is = Number { value: 32 }
// My Number-num2 is = Number { value: 6 }
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页