how to convert Option<&u8> to u8 - rust

i want to convert Option<&u8> to u8 so i will be able to print it
my code:
fn main() {
let v : Vec<u8> = vec![1, 2, 3, 4, 5];
let out_of_range = &v[100];
let out_of_range = v.get(100);
match out_of_range{
Some(&u8) => println!("data out of range: {}", out_of_range),
None => println!("bruh"),
}
}

Your match statement needs the introduction of a binding, not a type (the &u8 you used was not expected here).
Here Some(val) matches with something which is an Option<&u8>, thus val is a binding to the embedded &u8 (if not None, of course).
The example explicitly dereferences val as an illustration, and highlights the fact that val is not an u8 but a reference, but it's not required for the following operation (printing).
fn main() {
let v: Vec<u8> = vec![1, 2, 3, 4, 5];
for idx in [2, 20, 4] {
let at_index = v.get(idx);
match at_index {
Some(val) => {
// val has type &u8
let copy_of_val = *val; // not required, just for the example
println!("at {} --> {}", idx, copy_of_val);
}
None => println!("no value at {}", idx),
}
}
}

Related

Problems trying to get intersection of a Vector

I am having a problem whilst trying to get the intersection of two Vectors.
impl Solution {
pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> {
// Intended strategy:
// Store the first element into an intersect_result
// Iterate over the remaining elements for each element:
// Determine the intersection of the current element and the intersect result
// set intersect result to this.
// Sort the intersect result
// Return the intersect result back to the caller.
let len:i32 = nums.len() as i32;
let intersect_result:Vec<i32> = nums[0].clone();
for i in 1..len{
println!("i is: {}", i);
let temp_vec:Vec<i32> = nums[i as usize].clone();
// find the intersection of the current element with the intersect result
let unique_a:HashSet<i32> = temp_vec.into_iter().collect();
let unique_b:HashSet<i32> = intersect_result.clone().into_iter().collect();
intersect_result = unique_a.intersection(&unique_b).collect::<Vec<_>>();
}
vec![]
}
}
The error message I get is:
= note: expected struct `Vec<i32>`
found struct `Vec<&i32>`
This happens in the call unique_a.intersection().
Any thoughts guys?
You can add a map(|i| *i) in the iterator chain that causes the error:
intersect_result = unique_a.intersection(&unique_b).map(|i| *i).collect::<Vec<_>>();
When fixing this, the code also seems to work as intended. I think there are a few improvements possible (probably more, but these immediately tracked my attention):
use hashbrown::HashSet;
pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> {
let mut intersect_result: Vec<i32> = nums[0].clone();
for temp_vec in nums {
let unique_a: HashSet<i32> = temp_vec.into_iter().collect();
intersect_result = unique_a
.intersection(&intersect_result.into_iter().collect())
.map(|i| *i)
.collect::<Vec<_>>();
}
intersect_result
}
fn main() {
let a = vec![1, 2, 3];
let b = vec![2, 3, 4];
let c = vec![3, 4, 5];
let v = vec![a, b, c];
let res = intersection(v);
println!("res: {:?}", res);
}

How to slice to a particular element in a Vec?

What is the best way to slice a Vec to the first occurrence of a particular element?
A naive method demonstrating what I want to do:
fn main() {
let v = vec![1, 2, 3, 4, 5, 6];
let to_num = 5;
let mut idx = 0;
for x in &v {
if x != &to_num {
idx += 1
} else {
break;
}
}
let slice = &v[..idx];
println!("{:?}", slice); //prints [1, 2, 3, 4]
}
^ on the Rust playground
You can use <[T]>::split():
let slice = v.split(|x| *x == to_num).next().unwrap();
Playground.

How to idiomatically check if a 2-dimensional vector is a table? [duplicate]

Given a vector of vectors of some value T, ie. Vec<Vec<T>>.
What's the idiomatic way to check if the inner vectors have the same length? (without external dependencies)
That is, true if all the inner vectors have the same length, and false otherwise.
You can use the all method to check if all elements of an iterator match a predicate. Then just compare against the first element in the list.
fn main() {
let vec_of_vecs = vec![
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3, 4], // remove this to prove that it works for both cases
];
let all_same_length = vec_of_vecs
.iter()
.all(|ref v| v.len() == vec_of_vecs[0].len());
if all_same_length {
println!("They're all the same");
} else {
println!("They are not the same");
}
}
An other solution more generic and idiomatic in my opinion:
fn all_eq_len<'a, T, E: 'a>(collection: T) -> bool
where
T: IntoIterator<Item = &'a Vec<E>>,
{
let mut iter = collection.into_iter();
if let Some(first) = iter.next() {
let len = first.len();
iter.all(|v| v.len() == len)
} else {
true
}
}
And of course using itertools:
use itertools::Itertools;
vec_of_vecs.iter().map(|v| v.len()).all_equal()

Check if length of all vectors is the same in Rust

Given a vector of vectors of some value T, ie. Vec<Vec<T>>.
What's the idiomatic way to check if the inner vectors have the same length? (without external dependencies)
That is, true if all the inner vectors have the same length, and false otherwise.
You can use the all method to check if all elements of an iterator match a predicate. Then just compare against the first element in the list.
fn main() {
let vec_of_vecs = vec![
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3],
vec![1, 2, 3, 4], // remove this to prove that it works for both cases
];
let all_same_length = vec_of_vecs
.iter()
.all(|ref v| v.len() == vec_of_vecs[0].len());
if all_same_length {
println!("They're all the same");
} else {
println!("They are not the same");
}
}
An other solution more generic and idiomatic in my opinion:
fn all_eq_len<'a, T, E: 'a>(collection: T) -> bool
where
T: IntoIterator<Item = &'a Vec<E>>,
{
let mut iter = collection.into_iter();
if let Some(first) = iter.next() {
let len = first.len();
iter.all(|v| v.len() == len)
} else {
true
}
}
And of course using itertools:
use itertools::Itertools;
vec_of_vecs.iter().map(|v| v.len()).all_equal()

What is the idiomatic way to print a Vec as a string?

Updating my code to the new nightlies and it seems like they've gotten rid of to_string() for std::Vec
src/rust_mnemonic.rs:100:39: 100:50 error: type `collections::vec::Vec<&str>` does not implement any method in scope named `to_string`
rc/rust_mnemonic.rs:100 println!("mnemonic: {}", mnemonic.to_string());
You can use the :? specifier, which uses the Debug trait.
fn main() {
let v = vec![0u8, 1, 2, 3, 4, 5];
println!("{:?}", v);
}
If you want it as a String, then you can use format!:
fn main() {
let v = vec![0u8, 1, 2, 3, 4, 5];
let s = format!("{:?}", v);
println!("-->{}<--", s);
}

Resources