Hacker News new | past | comments | ask | show | jobs | submit login

You often don't need it at all;

  fn foo(x: f32) { println!("{}", x); }

  fn main() {
      let x = 5.0;
      foo(x);
  }
It will look at the signature for foo, and infer that x must be f32.



Whoa!

Isn't this kind of inference dangerous? It seems that whichever call comes first is used to infer the type, so a single added line of code can change the type of a variable…

  fn foo32(x: f32) { println!("{}", x); }
  fn foo64(x: f64) { println!("{}", x); }

  fn bar64() {
      let x = 5.0; // f64
      foo64(x);
      foo32(x);
  }

  fn bar32() {
      let x = 5.0; // f32, not f64
      foo32(x);
      foo64(x);
  }


That code doesn't compile. :) If you're ever curious about something like this, feel free to use the online playground, like so: https://play.rust-lang.org/?gist=c3c93fb796d5fa79f829baa3dec...

Here's the compiler error that you'd get:

    error[E0308]: mismatched types
     --> src/main.rs:7:13
      |
    7 |       foo32(x);
      |             ^ expected f32, found f64
    
    error[E0308]: mismatched types
      --> src/main.rs:13:13
       |
    13 |       foo64(x);
       |             ^ expected f64, found f32


Rust doesn't have coercions like C, so both of those fail to compile because using x: f64 with foo32 is an error for the first one and similarly x: f32 with foo64 for the second.


In addition to what the others said about this not working you can get this to work by providing a conversion to either of the calls, so this works:

  fn foo32(x: f32) { println!("{}", x); }
  fn foo64(x: f64) { println!("{}", x); }

  fn bar64() {
      let x = 5.0; // f64
      foo64(x);
      foo32(x as f32);
  }

  fn bar32() {
      let x = 5.0; // f32, not f64
      foo32(x);
      foo64(x as f64);
  }




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: