How to pad left in Rust? [duplicate] - string

This question already has answers here:
What is the easiest way to pad a string with 0 to the left?
(2 answers)
Closed 2 years ago.
I'm new to Rust and completely lost in the standard library. I do not want to add a crate just for padding.
How do I pad left a number with zeroes up to a certain width?
Lets say I have this code and I need the pad_left implementation.
fn main() {
let i = 5.to_string();
let padded_i = pad_left(i, 2);
}

The Rust Docs has an example of how you could format a number as a string with leading zeroes up to a certain width (5 in this example):
format!("Hello {:05}!", 5); // returns, "Hello 00005!"
format!("Hello {:05}!", -5); // returns, "Hello -0005!"
If you need to print the number, then you can replace the format! macro with print! or println! instead.

Related

How is Rust persuaded to do an explicit conversion rather than try to save references? [duplicate]

This question already has answers here:
In Rust, what's the difference between "shadowing" and "mutability"?
(1 answer)
Proper way to return a new string in Rust
(2 answers)
Return local String as a slice (&str)
(7 answers)
Why can't I return an &str value generated from a String?
(1 answer)
How do I make format! return a &str from a conditional expression?
(3 answers)
Closed 2 years ago.
How is the following made to work (safely)? There are serious downsides to using 'static.
fn whatever() {
let mut myslice = "goodbye"; //variable that lives, but not necessarily the whole program!
print!("{}", myslice);
{
let mystring = "hello".to_string();
myslice = &*mystring;
}
print!("{}", myslice);
}
The second print should produce 'hello'.
I encounter this problem commonly in lots of forms.
The open bracket could represent multiple things, like calling a function or using an if statement.
E.g.'If there are problems with the value in myslice and things are not working properly. {'
Working out the replacement, (which proved in the above example to be 'hello') is frequently no easy or quick matter, and involves code not to be touched unless it was proved there was a problem. As is normal in Rust, there are many alternatives to &*mystring (&mystring[..], : &str on the left, &*mystring, mystring.as_str(), etc.) but none explicitly manipulate the perfectly available, mutable and live long enough variable as if I had typed let found = "hello".to_string; myslice = &found;' outside the curly brackets. I have tried.clone()` in various places. Why does Rust make such a meal of this simple request? Obviously I am prepared to pay the minuscule processor time to actually do the
request.
I would like a general solution. However, it seems the above problem is explicitly with the type 'String'. e.g. let found = "hello"; let myslice = found; seems to work, even inside the brackets. (found is now &str - it does not seemed ever 'borrowed'.) Is the problem directly or indirectly tied up with not knowing length at compile time? Unfortunately and frequently this is not in my control, I have to use what crates decide to give.

Which conversion of a string literal into a String should be preferred [duplicate]

This question already has answers here:
How to create a String directly?
(3 answers)
What is the difference between these 3 ways of declaring a string in Rust?
(1 answer)
How do I convert between String, &str, Vec<u8> and &[u8]?
(1 answer)
Closed 2 years ago.
In Rust, there are several ways to create a String from a string literal:
fn main() {
let s_from = String::from("string"); // type on the right of the operator
let s_into: String = "string".into(); // type on the left of the operator
let s_to_string = "string".to_string(); // expresses type
let s_to_owned = "string".to_owned(); // expresses ownership
assert_eq!(s_from, s_into);
assert_eq!(s_from, s_to_string);
assert_eq!(s_from, s_to_owned);
}
Is there a rule in rust to follow a reading direction in relation to the operator?
Is there a reason to favour From/Into over to_string()/to_owned()?
Is there a reason to favour one of those over all the others?
With several developers working on a project, a mixture usage of those happens.

How to convert an integer to byte literal in Rust? [duplicate]

This question already has answers here:
Converting number primitives (i32, f64, etc) to byte representations
(5 answers)
Closed 3 years ago.
I am trying to convert an integer to byte literal in Rust:
for x in 0..10000 {
let key = x.to_???;
other_function(key);
}
Could not find it in the docs.
A byte literal is something like b'f', a literal value written down. You probably mean a byte, which is usually a u8, sometimes an i8. You can use the TryFrom-trait on recent rust:
use std::convert::TryFrom;
fn main() {
for i in 253..257 {
let u = u8::try_from(i).expect("Not all integers can be represented via u8");
println!("{}", u);
}
}
u inside the loop is an u8. The code will print 253, 254, 255 and crash on the iteration where i becomes larger than what a u8 can represent.

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.

How can I convert a one element string into a char? [duplicate]

This question already has answers here:
How do I get the first character out of a string?
(7 answers)
Closed 2 years ago.
I need to convert a one element &str into char. I was able to come up with this solution that also works for String:
fn main() {
let comma: &str = ",";
let my_char = comma.chars().nth(0).unwrap();
assert_eq!(my_char, ',');
}
Is there a better or shorter way to do it?
No huge improvements I can think of, but a few notes:
You could replace .nth(0) with .next(), which does basically the same thing.
You should ideally not use .unwrap(), since if the string is empty, your program will panic.
If you really must panic, ideally use .expect("msg"), which will give users a better idea of why you panicked.
Taking those together:
fn main() {
let comma: &str = ",";
let my_char = comma.chars().next().expect("string is empty");
assert_eq!(my_char, ',');
}
The only other thing to note is that "one element" is a somewhat dangerous thing to talk about. For example, "é" has one char, but "é" has two (the first is a pre-composed U+00E9, whilst the second is a regular e followed by a U+0301 combining ◌́).

Resources