24

Simple question: Where is sin()? I've searched and only found in the Rust docs that there are traits like std::num::Float that require sin, but no implementation.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kapichu
  • 3,346
  • 4
  • 19
  • 38

2 Answers2

31

The Float trait was removed, and the methods are inherent implementations on the types now (f32, f64). That means there's a bit less typing to access math functions:

fn main() {
    let val: f32 = 3.14159;
    println!("{}", val.sin());
}

However, it's ambiguous if 3.14159.sin() refers to a 32- or 64-bit number, so you need to specify it explicitly. Above, I set the type of the variable, but you can also use a type suffix:

fn main() {
    println!("{}", 3.14159_f64.sin());
}

You can also use fully qualified syntax:

fn main() {
    println!("{}", f32::sin(3.14159));
}

Real code should use the PI constant; I've used an inline number to avoid complicating the matter.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • It's interesting (and a bit confusing when coming from a c++/java background) that you don't use/import "math" but "Float". – Kapichu Jan 18 '15 at 15:24
  • 1
    Does not work. On first example, I get `error: type _ does not implement any method in scope named sin`, on second example, I get `error: unresolved name Float::sin`. $ rustc --version outputs `rustc 0.13.0-nightly (96a3c7c6a 2014-12-23 22:21:10 +0000)` – Kapichu Jan 18 '15 at 16:38
  • 2
    You will want to upgrade to the newest version of Rust. In preparation for the 1.0 release, there's lots of work going on! In this particular case, floating point literals now default to the type `f64` ([Relevant RFC](https://github.com/rust-lang/rfcs/blob/master/text/0212-restore-int-fallback.md)). If you want to get it to work, without upgrading, try `3.14f64.sin()`. – Shepmaster Jan 18 '15 at 16:46
  • 2
    @Kapichu, those errors are likely caused by those functions previously being part of the `std::num::FloatMath` trait (not the literal defaulting), however that will also be resolved by [upgrading](http://www.rust-lang.org/install.html) (I recommend [multirust](https://github.com/brson/multirust) too). – huon Jan 19 '15 at 00:17
-1

Float is Trait, include implementation, import this to apply for f32 or f64.

use std::num::Float;

fn main() {
    println!("{}", 1.0f64.sin());
}
uwu
  • 1,590
  • 1
  • 11
  • 21
  • Your answer isn't relevant till this date. The `Float` trait is removed. As mentioned by, @Shepmaster. – tripulse Sep 26 '19 at 06:35