Initialize array with consecutive integers [duplicate] - rust

This question already has answers here:
How can I initialize an array using a function? [duplicate]
(5 answers)
How do I collect into an array?
(10 answers)
Does Rust have a way to apply a function/method to each element in an array or vector?
(2 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
What is the simplest form of initializing an array with consecutive integers from 0 to N?
I have this code, but I think idiomatic Rust will look much simpler:
const NUM: u32 = 8;
fn main() {
let mut int_list: [u32; NUM as usize] = [0; NUM as usize];
for i in 0..NUM {
int_list[i as usize] = i;
}
println!("data: {:?}", int_list);
}
playground

Related

How can I swap parts of a string? rust [duplicate]

This question already has answers here:
How do I change characters at a specific index within a string in rust?
(2 answers)
What are the differences between Rust's `String` and `str`?
(14 answers)
Closed 3 months ago.
let mut hour = "sss"
let mut min = "lll"
I want to swap hour[0] as string and min[1] as string, how can I do that?

For loop is waiting for input before iterating [duplicate]

This question already has answers here:
Why does this read input before printing?
(3 answers)
How do I print output without a trailing newline in Rust?
(2 answers)
Closed 1 year ago.
I'm just learning Rust, and when I run the below code, it waits for my input before iterating through the for loop. Why does this happen, and how can I stop it?
pub fn whatever() {
for i in 1..121 {
print!("{} ", i);
}
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();
}

How do I push a string with a variable into a vector? [duplicate]

This question already has answers here:
How to create a formatted String out of a literal in Rust?
(2 answers)
How can I append a formatted string to an existing String?
(1 answer)
Closed 1 year ago.
I'm trying to solve a Kata where I'm asked to "count sheep". A function count_sheep is called with a positive integer as parameter. I'm supposed to return a string with a murmur: "1 sheep...2 sheep...3 sheep..."
This is what I have so far:
fn count_sheep(n: u32) -> String {
let mut Sheep_vec = String::new();
let mut i = 1;
while i <= n {
sheep_string = ("{} sheep..", i);
Sheep_vec.push(sheep_string);
i = i + 1;
}
Sheep_vec
}
I wanted to return the string analog to the println! macro, but that fails, because .push() doesn't support multiple argumentss.

How do I concatenate strings in a no_std environment? [duplicate]

This question already has answers here:
How can I use the format! macro in a no_std environment?
(5 answers)
A more convenient concatenation with a string literal in Rust
(3 answers)
How to format output to a byte array with no_std and no allocator?
(2 answers)
How to create a static string at compile time
(3 answers)
Closed 3 years ago.
I'm trying to concatenate two strings (&str) or convert a byte array in a string in Rust without using std. I saw core::str::from_utf8 but that's not what I'm looking for.
I'm searching something like
let b: [u8; 2] = [97, 98];
let result: &str = core::str::array_to_string(b); // "ab"
or
let a: &str = "Hello ";
let b: &str = "world !";
let result: &str = core::str::concatenate(a, b);

How to populate a vector with predefined capacity? [duplicate]

This question already has answers here:
What's the difference between len() and capacity()?
(2 answers)
How to allocate space for a Vec<T> in Rust?
(3 answers)
How do I generate a vector of random numbers in a range?
(2 answers)
Closed 3 years ago.
I am trying to populate a vector after initialising it with with_capacity() as the number of elements is known prior to its creation and it seems more efficient with it.
The following code does NOT populate with random values AT ALL: println!("{}", v.len()); outputs zero.
use rand::Rng;
fn main() {
const NUMBER_OF_RANDOM_NUMBERS: usize = 10;
let mut v = Vec::with_capacity(NUMBER_OF_RANDOM_NUMBERS);
for i in &mut v {
*i += rand::thread_rng().gen_range(1, 2^32);
}
println!("{}", v.len());
}
My thinking is after let mut v = Vec::with_capacity(NUMBER_OF_RANDOM_NUMBERS) a brand new vector gets initialised with 10 zeros and then using rand::thread_rng().gen_range(1, 2^32) to insert, or should I say, add a random number to each zero.
Am I missing something here?
with_capacity does not initialize the values of the vector, it just allocates space for them. From the documentation:
It is important to note that although the returned vector has the
capacity specified, the vector will have a zero length. For an
explanation of the difference between length and capacity, see
Capacity and reallocation.
This means that when your loop code is executed, there are no items in the vector, and therefore it loops a total of zero times. Resulting in no change in the vector.

Resources