i know this is something really simple but tell me whats wrong with data types , i didnt even manually decided , how did this went wrong? here is code :
fn main() {
let c = [1..100];
for number in c.iter() {
println!("{}",c[number]);
}
println!("Hello, world!");
}
here is error
error[E0277]: the trait bound `&std::ops::Range<{integer}>: std::slice::SliceIndex<[std::ops::Range<{integer}>]>` is not satisfied
--> src\main.rs:6:23
|
6 | println!("{}",c[number]);
| ^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
[1..100] is actually an array containing a range, [Range<i32>; 1]. Then .iter() iterates the array as a slice, producing an item of &Range<i32>. You can't index with that, but you could if you cloned it (w/ coercing the integers to usize), producing a new slice, but that would be out of range for c that contains only one item.
No, it doesn't. You can't create an array filled from a range like this.
You can get Rust to show you by purposely forcing a type mismatch, like:
|
2 | let c: () = [1..100];
| ^^^^^^^^ expected (), found array of 1 elements
|
= note: expected type `()`
found type `[std::ops::Range<{integer}>; 1]`
No, loop is an infinite loop. If your goal is to print 100 numbers, then that's not the way to do it.
fn main() {
let c = 1..100;
for number in c {
println!("{}", number);
}
println!("Hello, world!");
}
That works and prints numbers, because 1..100 (without []) is an iterator over a range of numbers. OTOH [] is an array, so [something] is an array of length 1 containing something.
You can have an array of ranges. Ranges don't contain the numbers, they are just a pair of (start, end) that doesn't contain or do anything until you start iterating it:
fn main() {
let c = [1..100, 5..20, 3..10, 9..99];
for range in &c {
println!("Abstract range from {} to {}", range.start, range.end);
}
println!("Hello, world!");
}
Abstract range from 1 to 100
Abstract range from 5 to 20
Abstract range from 3 to 10
Abstract range from 9 to 99
Hello, world!