Rust की मूल बातें
Reading User Input in Rust
Read a line with read_line, trim it and parse it into a number without crashing on bad input.
आप क्या सीखेंगे
- io::stdin().read_line
- trim and parse
- Handling bad input with match
From the keyboard to a number
- 1
read_line"36\n" - 2
trim()"36" - 3
parse::<u32>()Ok(36) - 4
age + 137
Text in, number out
read_line waits for the user to type a line and press Enter, then adds the text to a String. The text always arrives as a string, so numbers must be parsed before you calculate with them.
trim removes the newline that read_line keeps at the end. parse::<u32>() returns Ok with the number or Err when the text is not a number, and match handles both cases. The sample output uses the answers Ada and 36: in the online compiler, type your answers when the prompts appear.
मुख्य बातें
read_linekeeps the newline: call trim.- parse returns
Ok(number)or Err. - match handles both cases.
चलने योग्य Rust उदाहरण
Rust
main.rs
use std::io;
fn main() {
println!("What is your name?");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("failed to read");
let name = name.trim();
println!("How old are you?");
let mut age = String::new();
io::stdin().read_line(&mut age).expect("failed to read");
match age.trim().parse::<u32>() {
Ok(age) => println!("Hello, {name}! Next year you will be {}.", age + 1),
Err(_) => println!("Hello, {name}! That is not a number."),
}
}
What is your name?
How old are you?
Hello, Ada! Next year you will be 37.अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- मान्य संख्याओं का जोड़ ऐसी प्रविष्टियों को जोड़ें जो पूर्ण संख्याएँ हैं और बाकी सबको छोड़ दें, जैसे try/except खराब input को संभालता है. आसान
- Absolute Value Without abs Compute an absolute value with a condition. आसान