Hello there, I'm new to rust (and Programming in general). I'm trying to create a function that makes it easy to convert a string input directly to integer input . While the code I wrote works the compiler gives me a lot of warnings. what would be the better way to do this so the compiler doesn't get pissed off ?Because I'm new to rust and learning I'm trying to avoid using crates for the time being.
use std::io;
fn main() {
let mut a = String::new();
let a = toint(a);
println!("{}",a);
}
fn toint(x:String) -> i32{
let mut x = String::new();
io::stdin()
.read_line(&mut x)
.expect("No input");
x.trim().parse().expect("NaN")
}
"Like that"? Like what? Which part exactly did you think was impossible and why?
Note that Rust's type system is very uniform. You can pass any type to a function and return any type.1 And mutable references are just normal types like any other. People pass all sort of references to functions all the time. But it's not like this is specific to Rust. Indirection is a fundamental need and almost every language supports it (at most it's implicit).
1 Returning unsized types always requires indirection, but that's beside the point.
If the idea is to "convert a string to an int", as the title of this. thread and the function name indicate then why not take a string as an immutable input parameter &str and return a Result that contains the parsed int or an error. The given string may not be a number after all or the reading of stdin might fail.
Also, this function is called toint. And takes a String argument. That suggests it converts the given String to an integer. But it does not do that. It hides the fact that it does more than that, it reads a string from stdin. Better to call it 'read_int' or 'get_int' or whatever. In which case the 'x' parameter is not needed at all, just create the String in function.
I think this is a really important point about code design + maintainability: clarity of purpose, clarity of function names, avoiding side-effects. I have worked in some huge code bases (mostly Python) and misleading function names plus unexpected side-effects caused quite a few bugs. Of course, Python is notoriously easy to prototype (it's easy to shoot yourself in the foot), but these kind of issues cannot all be caught by the Rust compiler either (right?), so I think it's good to pay special attention to this - even when just trying out some code