Rust中使用read_line读取浮点数报错:expected struct `String`, found `f64` 求助
Fixing Rust Temperature Converter: Reading Floating-Point Input Correctly
Hey there! Let's get your temperature conversion program working smoothly. The error you're hitting makes total sense—read_line is designed to read text input into a String, not directly into a numeric type like f64. Here's how to fix it step by step:
Why the Error Happens
.read_line(&mut fahrenheit) | ^^^^^^^^^^^^^^^ expected struct String , found f64
The read_line method requires a mutable reference to a String because it reads the entire line of input (including the newline character) as text. You can't pass an f64 directly here—Rust's strict type system won't allow it.
Step-by-Step Fix
- Read input into a String first: Declare a mutable
Stringvariable to capture the user's input. - Clean up the input: Use
trim()to remove any leading/trailing whitespace (like the newline character from pressing Enter). - Convert the String to f64: Use the
parse()method to turn the cleaned text into a floating-point number. We'll add error handling here in case the user enters something that isn't a valid number. - Keep your conversion logic: Your temperature conversion logic looks solid—we'll keep that core functionality intact.
Modified Working Code
use std::io; // Don't forget to import the io module! fn main(){ println!("Enter fahrenheit: "); // Step 1: Create a mutable String to hold input let mut input = String::new(); // Step 2: Read input into the String io::stdin() .read_line(&mut input) .expect("Failed to read line"); // Step 3: Convert String to f64, with error handling let fahrenheit: f64 = input.trim() .parse() .expect("Please enter a valid number"); // Step 4: Run conversion and print result let temp_convert = fahrenheit_to_celsius(fahrenheit); println!("Converted to Celsius: {temp_convert}"); } // Renamed to follow Rust's snake_case convention for idiomatic code fn fahrenheit_to_celsius(x: f64) -> f64{ (x - 32.0) * 5.0 / 9.0 }
Extra Notes
- I added
use std::io;at the top—your original code was missing this import, which would have caused another error once the type mismatch was fixed! - Renamed functions and variables to follow Rust's standard snake_case convention (this makes your code feel more natural to other Rust developers).
- The
parse()method returns aResult, so usingexpect()gives a helpful error message if the user enters something non-numeric (like "abc" instead of 72). For more robust handling, you could use amatchexpression to prompt the user again instead of panicking.
内容的提问来源于stack exchange,提问作者De.Shaw
相关产品推荐
相关产品推荐

