Skip to content

Instantly share code, notes, and snippets.

@NickyMeuleman
Created July 22, 2021 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickyMeuleman/379654be0e202bb6054cb44b034ec43f to your computer and use it in GitHub Desktop.
Save NickyMeuleman/379654be0e202bb6054cb44b034ec43f to your computer and use it in GitHub Desktop.
Rust: accessing elements in vectors
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"
}
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"
}
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"
}
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