How to get absolute value of a number in Rust?
Hello colleagues! I just started learning Rust after Python, and I have a seemingly simple problem. In Python, I'm used to using `abs(-5)` and getting 5. Now I'm trying to do the same in Rust, but the compiler gives errors.
Here's my code:
```rust
fn main() {
let x = -5;
let y = abs(x);
println!("Absolute value: {}", y);
}
```
The compiler says: "error[E0425]: cannot find function `abs` in this scope". I tried writing `x.abs()`, and it worked for integers. But when I tried to do the same with floating-point numbers:
```rust
fn main() {
let a: f64 = -3.14;
let b = a.abs();
println!("{}", b);
}
```
This also works. But what if I want to write a universal function that accepts both integers and floats?
No answers yet.
Log in to leave an answer