struct之impl下的from.into和new方法,代码如下,请过目…
#[derive(Debug)]
struct Myname{
name:String,
}
impl From<String> for Myname{
fn from(n:String) -> Self{//Self可以换成Myname
Myname{name:n}
}
}
impl Myname{
fn new(n:String) -> Self{//Self可以换成Myname
Myname{name:n}
}
}
fn main(){
// let n = Myname::from("oh no.".to_string());
// println!("{:?}",n.name);
let m :Myname= "why?".to_string().into();//into能根据类型推导哦
println!("{:?}",m.name);
let m = Myname::new("oh my god.".to_string());
println!("{:?}",m.name);
}
运行代码输出如下内容:
"why?"
"oh my god."