Hi, I am new to Rust and I am using rustings to get familiar with it. One of the question has a bonus question: what would make a.len() also return true. I have no idea and couldn't find any one mentioning it on the internet so I suppose it's very trivial. Here is the question:
// primitive_types3.rs
// Create an array with at least 100 elements in it where the ??? is.
// Execute `rustlings hint primitive_types3` for hints!
// I AM NOT DONE
fn main() {
let a = ??? // make it something like [7, 100] is the obvious solution.
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
}
}
Here is the bonus question:
Bonus: what are some other things you could have that would return true
for a.len() >= 100?
This looks like a fairly open-ended question, looking for exploration. What about searching on rust's docs for functions named len? Not all of those are useful, but there are quite a few which you could create. It also includes some trait methods, like ExactSizeIterator::len, which could lead towards more different things you could make.
On top of regular slices, you really have anything that can turn into a slice:
(Box::new([0; 2]) as Box<[u8]>).len() == 2
(Arc::new([0; 2]) as Arc<[u8]>).len() == 2
(Rc::new([0; 3]) as Rc<[u8]>).len() == 3
vec![0, 1, 2, 3].len() == 4 //vec! is a macro for making a Vec.
Any of the types for which ExactSizeIterator is implemented. This includes the double-ended range mentioned above.
The collections, Vec, HashMap, HashSet, BTreeMap, BTreeSet, etc.
I'm not including unsafe variants, because they're all basically the same, except for you need to do (*value).len(), or maybe insert a get_mut_unchecked or something.
And, of course, you can create your own custom struct and implement the len method directly on it:
struct VeryLong;
impl VeryLong {
fn len(&self) -> usize {
1000
}
}
fn main() {
let a = VeryLong;
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
}
}
Originally I thought it must be something related to array but now I read the question again I think it's just an open-ended question. Thanks for the link, I will go over it tomorrow.
Thanks for the help. This is what I later had in mind. But I think the answer using ".." may be what the bonus question was orignally intended so I marked it as solution. What a great community!