This question already has answers here:
Is there a good way to convert a Vec<T> to an array?
(1 answer)
How to convert a Vec into an array without copying the elements?
(3 answers)
Closed 27 days ago.
I found numerous answers related to converting vectors into arrays, but all deal with simple types inside the vector, which in my case doesn't work.
I have a Vec<(String, PayloadType)> where PayloadType is a rich enum.
I need to convert it into an array [(String, PayloadType), _].
Some attempts:
try_into():
492 | Payload::from(v[..].try_into().unwrap())
| ^^^^^^^^ the trait `TryFrom<&[(String, mpl_token_auth_rules::payload::PayloadType)]>` is not implemented for `[(String, mpl_token_auth_rules::payload::PayloadType); _]`
into_inner():
492 | Payload::from(v.into_inner().unwrap())
| ^^^^^^^^^^ method not found in `Vec<(String, mpl_token_auth_rules::payload::PayloadType)>`
What's the right way to do it?
PS, the broader goal is to convert a hashmap like this:
pub struct Payload {
map: HashMap<String, PayloadType>,
}
into an array like this:
[(String, PayloadType); N]
I went about it by converting it to Vec first, but open to a better way.
Related
This question already has an answer here:
The size for values of type `T` cannot be known at compilation time when using mem::size_of::<T> as an array length
(1 answer)
Closed 2 years ago.
I want to convert T to bytes array,
fn to_byte<T: Sized>(a: T) -> [u8; std::mem::size_of::<T>()] {
unimplemented!()
}
when I call this function let a = to_bytes::<u32>(); the type will be confirmed, but got error:
error[E0277]: the size for values of type `T` cannot be known at compilation time
--> lab/test-bit/src/main.rs:3:56
|
3 | fn to_byte<T: Sized>(a: T) -> [u8; std::mem::size_of::<T>()] {
| - this type parameter needs to be `Sized` ^ doesn't have a size known at compile-time
|
Stable Rust does not support using generic parameters in const expressions.
In nightly, the code should work as long as you enable const_generics and const_evaluatable_checked.
In any case, you don't need the Sized bound, it is implicit.
This question already has answers here:
How do I create a Vec from a range and shuffle it?
(2 answers)
Closed 2 years ago.
Suppose I had the following variable:
let mut n: &[((usize, usize), (usize, usize))];
I'd like to shuffle some data in this variable. I tried:
rng.shuffle(&mut n); // rng is of type rand::Rng
which of course leads to a compiler error complaining that the trait RandCore isn't implemented for that type. I don't really mind implementing it, but I'd hate to have to define a trait implementation for every variation of that type (e.g. (usize, isize), ((usize, isize), (usize, isize), (isize, usize)), etc) that I have in my code.
Is there another way of "automatically" defining this trait (like using macros of some sort)?
You have the arguments the wrong way round. It should be n.shuffle(&mut rng). RandCore is the trait for an rng, not a value to be shuffled. You should then find SliceRandom is implemented for all slices if you use it.
This question already has answers here:
How can I store multiple elements in a Rust HashMap for the same key?
(1 answer)
How do I create a map from a list in a functional way?
(3 answers)
Closed 3 years ago.
I am pretty new to rust, so I have a bit of trouble with the borrow checker. I have a json object which is a vector of the form:
Vec<(String, Option<char>, String)>.
I want to be able to convert this vector into a hash map in order to allow for quick access of each element. Originally, each tuple was unique, and the user would pass a pair of a string and a char, so I had a hashmap of which was of the form HashMap<(String, Option<char>), String>. The conversion function was just an iteration over the original vector passed as a json object like so:
let new_transition_function: Vec<(String, Option<char>, String)> = origin
.transition_function
.iter()
.map(|(x, y, z)| ((x.to_owned(), y.to_owned()), z.to_owned()))
.collect();
However, when the third element is non-unique, the value is jsut replaced in the hashmap, when I need to keep each value. How can I most efficiently and idiomatically transform the old vector of Vec<(String, Option<char>, String)> to a HashMap<(String, Option<char>), Vec<String>)>?
This question already has answers here:
How does one create a HashMap with a default value in Rust?
(4 answers)
Converting from Option<String> to Option<&str>
(5 answers)
Closed 3 years ago.
I have a HashMap<_, String>for which I would like to either get the corresponding value of a key or return a default string. The most obvious approach would be to just use unwrap_or, but this fails with an type error:
error[E0308]: mismatched types
--> src/main.rs:11:44
|
11 | let val = hashmap.get(key).unwrap_or("default");
| ^^^^^^^^^ expected struct `std::string::String`, found str
|
= note: expected type `&std::string::String`
found type `&'static str
I can work around this using an expression like if let Some(val) = hashmap.get(key) { val } else { "default" }, but I was wondering if there is a cleaner approach.
It appears that the issue is that Rust does not automatically perform Deref coercion on the Option<&String>, thus you must explictly convert to a &str using something like Option::map_or:
let val = hashmap.get("key").map_or("default", String::as_str);
While this is the most direct method, there are several other alternatives for Deref coercion in this related answer: https://stackoverflow.com/a/31234028/1172350
This question already has an answer here:
How to filter a vector of custom structs?
(1 answer)
Closed 4 years ago.
I have a vector and trying to create a new vector by filtering. It does not work and I don't know why:
fn example(data: Vec<f64>, missing_value: f64) {
let dude = data
.iter()
.filter(|&x| *x != missing_value)
.collect::<Vec<f64>>();
}
error[E0277]: a collection of type `std::vec::Vec<f64>` cannot be built from an iterator over elements of type `&f64`
--> src/lib.rs:5:10
|
5 | .collect::<Vec<f64>>();
| ^^^^^^^ a collection of type `std::vec::Vec<f64>` cannot be built from `std::iter::Iterator<Item=&f64>`
|
= help: the trait `std::iter::FromIterator<&f64>` is not implemented for `std::vec::Vec<f64>`
There is a single implementation of FromIterator for Vec, and this implementation collects values of T from the same type T, i.e., it is not possible to convert T into an arbitrary type U and collect its elements at the same time.
In your case, you want to collect an iterator of &f64 into a vector of f64, therefore, you need to convert by cloning/copying and then collect.
self.data.iter().filter(|&&x| x != self.missing_value).cloned().collect::<Vec<f64>>();
If you have ownership of the vector, it is possible to iterate over f64 instead of &f64 by using into_iter.
self.data.into_iter().filter(|&x| x != self.missing_value).collect::<Vec<f64>>();