Hey Everyone, Brand new to Rust, just started this week, I am posting just to get some basic understanding of borrow versus copy and trying to get used to using this community.
Here is my problem, I wrote a function to produce the value of the data type as a string, I also take user input into a mutable variable of string type. I try to read the value of the string variable into the function, and it used to give me the data type of the string, but after I change the mutable variable from a string type to a f64, when I try to pass the string variable to the function to read the data type it gives me a error that string doesn't have copy trait, does that mean that the only way I would be able to get the data type would be to clone the string and send it too the function?
Here is the main function body of the code with the input from the user of the string and the call to the data type function:
let mut user_input_float = String::new();
io::stdin()
.read_line(&mut user_input_float)
.expect("Failed to read line");
println!("You entered: {}", user_input_float);
println!("Type of what you entered: {}", type_of(user_input_float));
let user_input_float: f64 = user_input_float.trim().parse().expect("Please type a number!");
println!("Your input float after parsing: {}", user_input_float);
println!("Your input float data type after parsing: {}", type_of(user_input_float));
Here is the functio:
fn type_of<T>(_: T) ->&'static str {
type_name::<T>()
//:: <T> is an associated function of type_name that acts on
//Type_name
}
I'm also a little confused by the function, is a empty data type, then the variable reference I pass it copied to T, which type_name then acts on? I copied this code from somewhere else in this forum so if someone would explain how the purpose is that would be great too.
Here is my compiler error message:
|
31 | ...et mut user_input_float = String::new();
| -------------------- move occurs because `user_input_float` has type `String`, which does not implement the `Copy` trait
...
38 | ...rintln!("Type of what you entered: {}", type_of(user_input_float));
| ---------------- value moved here
39 | ...
40 | ...et user_input_float: f64 = user_input_float.trim().parse().expect("Pl...
| ^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
|
= note: borrow occurs due to deref coercion to `str`
This code is really just to learn the language and get some basic practice, if any one wants to take some time to explain these concepts to a newbie I would greatly appreciate it, and send good coding karma your way. Really looking to learn from you guys and be part of the Rust community