Hi, I am begginer. I have a problem with "print!":
use std::io;
fn main() {
print!("What is your fist name?");
let mut f_name = String::new();
io::stdin()
.read_line(&mut f_name)
.expect("Fale to read line");
println!("What is your last name?");
}
Why first output "stdin"? I need something this:
"What is your fist name?" Anton
"What is your last name?"
Note that stdout is frequently line-buffered by default so it may be necessary to use io::stdout().flush() to ensure the output is emitted immediately.
For efficiency, Rust will buffer an entire line (i.e. until a newline) before sending it to the terminal. If you want it to print earlier than that, call io::stdout().flush().unwrap();.
The string value in "stdin" ends with "\n". How to disable newline?
use std::io::{self, Write};
fn main() {
print!("What is your fist name? ");
io::stdout().flush().unwrap();
let mut f_name = String::new();
io::stdin()
.read_line(&mut f_name)
.expect("Fale to read line");
print!("What is your last name? ");
io::stdout().flush().unwrap();
let mut l_name = String::new();
io::stdin()
.read_line(&mut l_name)
.expect("Fale to read line");
print!("What letter grade do you deserve? ");
io::stdout().flush().unwrap();
let mut grade = String::new();
io::stdin()
.read_line(&mut grade)
.expect("Fale to read line");
print!("What is your age? ");
io::stdout().flush().unwrap();
let mut age = String::new();
io::stdin()
.read_line(&mut age)
.expect("Fale to read line");
let age: i32 = age.trim().parse().expect("Please type a number");
io::stdout().flush().unwrap();
print!("Name: {f_name}, {l_name}");
print!("Grade: {grade}");
println!("Age: {age}");
}
I need something like this:
"What is your fist name?" Anton
"What is your last name?" Chehov
"What letter grade do you deserve?" A
"What is your age?" 12
Name: Anton, Chehov
Grade: A
Age: 12
I’ve used a minute to write out your example, with a bit of ChatGPT assistence
use std::io::{self, Write};
use std::str::FromStr;
#[derive(Debug)]
enum Grade {
A,
B,
C,
D,
F,
}
impl FromStr for Grade {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"A" => Ok(Grade::A),
"B" => Ok(Grade::B),
"C" => Ok(Grade::C),
"D" => Ok(Grade::D),
"F" => Ok(Grade::F),
_ => Err(()),
}
}
}
fn main() {
let mut input = String::new();
print!("What is your first name? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read line");
let first_name = input.trim().to_string();
input.clear();
print!("What is your last name? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read line");
let last_name = input.trim().to_string();
input.clear();
print!("What letter grade do you deserve? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read line");
let grade: Grade = input.trim().parse().expect("Failed to parse grade");
input.clear();
print!("What is your age? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read line");
let age: u32 = input.trim().parse().expect("Failed to parse age");
println!();
println!("Name: {last_name}, {first_name}");
println!("Grade: {:?}", grade);
println!("Age: {age}");
}
I'm not an expert, but as I see the rust language requires a lot of knowledge to write simple things. If we compare the code from chat_GPT with the c++ code, then the second one is much simpler. I don't see the benefits of the rust language yet. It seems that at some point, programming languages ceased to be a tool for solving problems and became one big task themselves.
c++:
#include <iostream>
#include <string>
int main() {
using namespace std;
cout << "What is your fist name? ";
string f_name, l_name;
getline(cin, f_name);
cout << "What is your last name? ";
getline(cin, l_name);
cout << "What letter grade do you deserve? ";
char grade;
cin >> grade;
cout << "What is your age? ";
int age;
cin >> age;
cout << "Name: " << l_name << ", " << f_name << "\nGrade: " << ++grade
<< "\nAge: " << age << endl;
return 0;
}
You should at least be adding << flush to the C++.
"programming languages to be a tool for solving problems"
Your better off going with python (as example) for that. (until you hit performance wall.)
Rust is a language you give others the program you have made. The time it takes to sort out the issues found if you/someone test what you wrote in a different language isn't a trivial amount. You also have a higher risk of a bug leading to data corruption going unnoticed.
The main reason it’s a bit tedious is that Rust’s standard library aims to be minimal. Every API in the standard library is fixed, it can never change in a major way, which is why non-essential API is better served as a crate. With Rust’s package manager, that’s not much of a hassle anyways. Depending on what exactly you want, there's various kinds of possible behaviors. How do you want to handle erroneous input? Do you want line-editor features such as navigating a cursor with arrow keys? To list just two crates I could find text_io - Rust, promptly - Rust.
As I wrote, I am not an expert. But what I noticed is that for the sake of security and avoiding potential errors, usability and simplicity suffer. I would compare the rust language to a 10-page permission form without which you will not be allowed to do anything. Compared to C++, it is a freer language, albeit a dangerous one. Perhaps it would be worthwhile to work a little with Okama's razor with the rust language, at least in solving simple problems. I don’t know much, don’t get angry, this is just a fresh look from the layman from the outside.
This tradeoff is part of what attracted me to rust; I've spent a lot of time teaching coworkers the C++ UB rules they accidentally break. I've had to spend way too much time arguing with coworkers who think their UB is ok because (some complicated argument based on their understanding of Intel processors) by looking up ISO rules and showing them their argument doesn't fit its framework. And when that fails waste several weeks producing a test case which surfaces the UB in a way that is obviously broken to them. I became the permission slip.
Fortunately some crates such as promptly fill out the permission slip for you.
If you had enough experience in the language, you would clearly see that it's not any harder to learn than any other language of its league, and it's not any more complicated than it absolutely needs to be. It's got its own idioms, libraries, tooling, and after getting used to, it's perfectly fine to use.
If you think that C++ is easy, you probably don't know C++, either. That language is full of bear traps, and you will end up suffering later, and a lot more, while trying to debug mysteriously disappearing objects, UaFs, and stuff that's changing while it shouldn't be.
It's easy to hate on Rust if you never worked on a large,
complex code base. But please, if you can't have an informed opinion based on actual experience, don't go around a Rust forum hating on Rust. Nothing good results from that. You'll only frustrate others as well as yourself (because people will push back). That's a waste of time for everyone.
You are comparing apples to oranges. Your C++ code completely ignores error handling, and what's worse, you don't even know about it (because nothing forces you to at least acknowledge the presence of error conditions in the code).
Quite a bold claim from a beginner. If you think that you could have designed the language better, you are cordially invited to do so.
I did not write that I hate the rust language. If I hate something, I'm not interested in it. I am a researcher, for many years of work I got used to looking at things from different angles. Since languages do not exist without native speakers, it is obvious that the rust programming language has its users. I can say now I'm learning both the rust language and its users...
“Ah, Mr. Occam’s Razor. The problem Bernard, is that what you and I do you is so complicated. We practice witchcraft. We speak the right words, and we create life itself out of chaos. William of Occam was a thirteenth century monk. He can’t help us now Bernard; he would have us burned at the stake.”
FWIW, toy programs being verbose in Rust is one of the most common complaints beginners have about the language, and is due to the language wanting to have a minimal and flexible standard library rather than its security or other features. Your example code isn't verbose because Rust wants to be verbose for no reason, or that no one has thought to simplify it before, instead in Rust the philosophy is generally that if something can be written in a library instead of including it in std, then it should be.
For example, here's my attempt at writing your code
use std::io::{self, Write};
fn main() {
let f_name = prompt_string("What is your first name?");
let l_name = prompt_string("What is your last name?");
let grade = prompt_string("What letter grade do you deserve?");
let age = prompt_number("What is your age?");
println!("Name: {f_name}, {l_name}");
println!("Grade: {grade}");
println!("Age: {age}");
}
fn prompt_string(prompt: &str) -> String {
print!("{prompt} ");
let _ = io::stdout().flush();
let mut s = String::new();
io::stdin().read_line(&mut s).expect("Failed to read line");
s.trim().to_string()
}
fn prompt_number(prompt: &str) -> i32 {
let s = prompt_string(prompt);
s.trim().parse().expect("Please type a number")
}
Similar helper functions could technically be added to the standard library, but Rust's philosophy is such that they shouldn't be, because it's easy to write them yourself if you need them or to make/use a library that defines them, and they are quite inflexible.
Sounds to me that you would have to write a lot more C++ or C before you start to see the the benefits of Rust in terms of greatly helping one avoid stupid (often subtle) mistakes that cause programs to fail by crashing at random or randomly producing incorrect results. You would have to have experience of languages like Python and Javascript before appreciating the performance benefits of Rust.
I too get that feeling sometimes. However Rust is certainly focused on solving the real problems that exist with other languages that compile to high performance executables, for example C and C++. Unfortunately it seems unavoidable to introduce a little burden on the programmer to achieve this, which makes Rust look a bit heavy weight for trivial programs as in your example.
This is number 1 reason for me. I used to crash many computers just so I could generate patterns to look at. My rust programs at worst "panic" a message to my terminal.
I still couldn't choose. C++ is an old technology, but understandable and proven. Rust is a new language and promising. It turns out I'm currently learning both languages, I don't know how justified it is, but knowledge of the C ++ language helps to understand the Rust language. The C++ language is a testing lab, and the rust language is a serial production language. I think the ability to read C++ code is useful to rewrite code in rust.
P.S. I do not understand everything from WHAT is written, but what is clear to me is that there is no perfection in the world.
Graydon Hoare:
I would have traded performance and expressivity away for simplicity -- both end-user cognitive load and implementation simplicity in the compiler -- and by doing so I would have taken the language in a direction broadly opposed to where a lot of people wanted it to go.