Created
July 22, 2021 15:23
-
-
Save NickyMeuleman/379654be0e202bb6054cb44b034ec43f to your computer and use it in GitHub Desktop.
Rust: accessing elements in vectors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::convert::TryFrom; | |
fn main() { | |
let names = vec!["Daniel", "Max", "Lewis"]; | |
let [daniel, max, lewis] = <[&str; 3]>::try_from(names).ok().unwrap(); | |
dbg!(daniel, max, lewis); | |
// daniel = "Daniel" | |
// max = "Max" | |
// lewis = "Lewis" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let names = vec!["Daniel", "Max", "Lewis"]; | |
let daniel = names[0]; | |
let max = names[1]; | |
let lewis = names[2]; | |
dbg!(daniel, max, lewis); | |
// daniel = "Daniel" | |
// max = "Max" | |
// lewis = "Lewis" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let names = vec!["Daniel", "Max", "Lewis"]; | |
let [daniel, max, lewis] = match names.as_slice() { | |
[] => panic!("the vector has length 3"), | |
[first, second, third] => [first, second, third], | |
[..] => panic!("the vector has length 3"), | |
}; | |
dbg!(daniel, max, lewis); | |
// daniel = "Daniel" | |
// max = "Max" | |
// lewis = "Lewis" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let names = vec!["Daniel", "Max", "Lewis"]; | |
match names.as_slice() { | |
[] => println!("empty"), | |
[first, rest @ ..] => println!("first name: {:?}, rest of names: {:?}", first, rest), | |
} | |
// first name: "Daniel", rest of names: ["Max", "Lewis"] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment