You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//在match语句中使用条件语句进行判断match time_of_day {
x if x < 22 => Some(5),
x if x < 24 => Some(0),
_ => None,}//将Option转为Result类型使用map_or,into函数对于实现了Into特征的类都可以进行类型转换assert_eq!(
generate_nametag_text("Beyoncé".into()).map_or(Err("`name` was empty; it must be nonempty."), |v| Ok(v)),Ok("Hi! My name is Beyoncé".into()));//?可以提取Option和Result中Some()和Ok()中的值,如果是None或Err则会返回None或Errlet qty = item_quantity.parse::<i32>()?;//Vec的pop方法返回的是Option类型whileletSome(Some(integer)) = optional_integers.pop(){assert_eq!(integer,cursor);
cursor -= 1;}//Box<dyn Trait> 可以动态分配,实现多态
//问题2,conversions文件中的as_ref_mut.rsfnnum_sq<T:AsMut<u32>>(arg:&mutT){// TODO: Implement the function body.//为什么不能是*arglet num = *arg.as_mut();//正确//let num = *arg;错误*arg.as_mut() = num * num;}//问题3,tests文件中的test5unsafefnmodify_by_address(address:usize){// TODO: Fill your safety notice of the code block below to match your// code's behavior and the contract of this function. You may use the// comment of the test below as your format reference.unsafe{// todo!("Your code goes here")let a_mut = address as*mutu32;//正确//let a_mut = address as *mut usize; 错误//为什么改成u32就对了,usize不对*a_mut = 0xAABBCCDD;}}//问题4,tests文件中的test6.rsunsafefnraw_pointer_to_box(ptr:*mutFoo) -> Box<Foo>{// SAFETY: The `ptr` contains an owned box of `Foo` by contract. We// simply reconstruct the box from that pointer.letmut ret:Box<Foo> = unsafe{Box::from_raw(ptr)};unsafe{
ret.b = Some("hello".to_string())//*ret.b = Some("hello".to_string()) 错误//自动解引用是如何实现的};
ret
}