How can I ask for an optional input with dialoguer? [duplicate] - rust

This question already has an answer here:
How to parse an empty string into a None?
(1 answer)
Closed 2 months ago.
I'm trying to get an optional input from dialoguer:
let name: Option<String> = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Name")
.interact()
.unwrap();
but I was not able to find a feature in dialoguer that supports this. Is there a piece of the API that I'm missing, or will I simply have to check for an empty string?

You can convert an empty string into a None using bool::then
let name: Option<String> = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Ferret's name")
.interact()
.map(|s: String| s.is_empty().not().then(|| s))
.unwrap();

Related

concat string using format!() and return to &'static str [duplicate]

This question already has answers here:
Return local String as a slice (&str)
(7 answers)
How to concatenate static strings in Rust
(3 answers)
Closed 2 years ago.
This post was edited and submitted for review 10 months ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I'll get error when compiled: 'returns value referencing data owned by the current function'
here's the code:
fn return_static_str(a: &'static str, b: &'static str) -> &'static str {
format!("{} {}", a,b).as_str()
}
fn main() {
let s = return_static_str("Hello ", "World!");
}
using return as_ref() get same issue.

Does Rust do some magic to interpret multiple ampersands (&)? [duplicate]

This question already has answers here:
What is the relation between auto-dereferencing and deref coercion?
(1 answer)
What are Rust's exact auto-dereferencing rules?
(4 answers)
Closed 2 years ago.
All the commented lines below are valid. How do multiple & have the same impact? Does Rust do some magic to interpret multiple &s?
// All commented code is also valid - wondering how?
let string_a = String::from("String A");
let str_a: &str = &string_a;
// let str_a: &str = &&&&&string_a; // --> this is valid statement
let mut str_option: Option<&str>;
str_option = Some(str_a);
// str_option = Some(&str_a); // --> this is valid statement
// str_option = Some(&&str_a); // --> this is also valid statement

How do I convert a String or str& into a Vec<String>? [duplicate]

This question already has answers here:
Split a string and return Vec<String>
(2 answers)
Closed 2 years ago.
A function I want to use requires a Vec<String> as parameter input.
What I have instead is either a string slice (&str) or a String.
My attempt:
let options_vec: Vec<String> = options.split(char::is_withespace).collect::<Vec<_>>();
The error I'm getting is:
value of type `std::vec::Vec<std::string::String>` cannot be built from `std::iter::Iterator<Item=&str>
split returns impl Iterator<Item = &str>, you need explicitly convert its items to String, for example like this:
let options_vec: Vec<String> = options
.split(char::is_whitespace)
.map(ToString::to_string)
.collect::<Vec<_>>();

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.

Is there an alternative to read_line that doesn't add anything to the input? [duplicate]

This question already has answers here:
Remove single trailing newline from String without cloning
(6 answers)
How to read an integer input from the user in Rust 1.0?
(8 answers)
Closed 4 years ago.
I am making a program that asks a user's age:
use std::io;
fn main() {
println!("How Old Are You?");
let mut age = String::new();
io::stdin().read_line(&mut age).expect("Failed to get age");
println!("You are {} years old!", age);
}
Once the user enters their age (8 for example) read_line inserts a '\n' to what the user inputs. The result looks like
You are 8
years old!
I know I can use something like this to remove the '\n' before displaying the age:
let age = age.trim();
Is there an alternative I could use to read user input simply that won't add anything to the variable.

Resources