// Note the _single_ quotes, these are different from the double quotes // you've been seeing around. let my_first_initial = 'C'; if my_first_initial.is_alphabetic() { println!("Alphabetical!"); } else if my_first_initial.is_numeric() { println!("Numerical!"); } else { println!("Neither alphabetic nor numeric!"); }
let your_character = 'B';// Finish this line like the example! What's your favorite character? // Try a letter, try a number, try a special character, try a character // from a different language than your own, try an emoji! if your_character.is_alphabetic() { println!("Alphabetical!"); } else if your_character.is_numeric() { println!("Numerical!"); } else { println!("Neither alphabetic nor numeric!"); } }
变量名为 a 的数组将包含 5 个元素,这些元素的值初始化为 3。这种写法与 let a = [3, 3, 3, 3, 3]; 效果相同,但更简洁。 这道题就很简单了
1 2 3 4 5 6 7 8 9 10
fn main() { let a = [1; 100];
if a.len() >= 100 { println!("Wow, that's a big array!"); } else { println!("Meh, I eat arrays like that for breakfast."); panic!("Array not big enough, more elements needed") } }
fn main() { let cat = ("Furry McFurson", 3.5); let (name, age)= cat;
println!("{} is {} years old.", name, age); }
Ex 6
即前面说的使用句点访问元组元素
1 2 3 4 5 6 7 8 9
#[test] fn indexing_tuple() { let numbers = (1, 2, 3); // Replace below ??? with the tuple indexing syntax. let second = numbers.1;
assert_eq!(2, second, "This is not the 2nd number in the tuple!") }
05_vecs(&8.1)
Ex 1
建立一个和数组a一样的vector
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
fn array_and_vec() -> ([i32; 4], Vec<i32>) { let a = [10, 20, 30, 40]; // a plain array let v = vec![10, 20, 30, 40];// TODO: declare your vector here with the macro for vectors
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> { for element in v.iter_mut() { // TODO: Fill this up so that each element in the Vec `v` is // multiplied by 2. *element *= 2; }
// At this point, `v` should be equal to [4, 8, 12, 16, 20]. v }
fn vec_map(v: &Vec<i32>) -> Vec<i32> { v.iter().map(|element| { // TODO: Do the same thing as above - but instead of mutating the // Vec, you can just return the new number! element * 2 }).collect() }
#[cfg(test)] mod tests { use super::*;
#[test] fn test_vec_loop() { let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect(); let ans = vec_loop(v.clone());
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>()); }
#[test] fn test_vec_map() { let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect(); let ans = vec_map(&v);
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>()); } }