De.Shaw
De.Shaw

Reputation: 23

Rust Read_line 'expected struct string, found f64'

I'm new in rust and stuck in the error below, and i could not find any clue on it. Anyone can point me out? I got no idea how to define the read_line in float.

.read_line(&mut fahrenheit) | ^^^^^^^^^^^^^^^ expected struct String, found f64

fn main(){
    println!("enter fahrenheit: ");
    //io::stdin() .read_line(&mut index) .expect("Failed to read line");
    let mut fahrenheit: f64 = 66.66;

    io::stdin()
        .read_line(&mut fahrenheit)
        .expect("fail to read");


    
    let tempConvert = fahrenheitToCelsius(fahrenheit);
    println!("convert from {tempConvert}");
}

fn fahrenheitToCelsius(x: f64) -> f64{  
    let mut gt: f64;
    gt = (x - 32.00) * 5.00 / 9.00;
    gt
}

Upvotes: 1

Views: 201

Answers (1)

jthulhu
jthulhu

Reputation: 8688

read_line will read a string from stdin, and it needs a buffer to put it in, which is supposed to be argument you pass it. If, then, you want to convert it, it's your job: it won't do that on its own. Thus the type error. To achieve what you want, simply create a buffer, then parse it.

  let mut buffer = String::new();
  io::stdin().read_line(&mut buffer).expect("Failed to read");
  let fahrenheit = buffer.trim().parse::<f64>().expect("Failed to parse as `f64'");

Note that in your code, the generic argument of parse might be left implicit since your fahrenheitToCelsius function might be enough for the compiler to figure out the type to perform the conversion to.

Upvotes: 4

Related Questions