算术

fn interproduct(a: i32, b: i32, c: i32) -> i32 {
    return a * b + b * c + c * a;
}

fn main() {
    println!("result: {}", interproduct(120, 100, 248));
}

这是我们第一次看到除 main 之外的函数,不过其含义应该很明确:它接受三个整数,然后返回一个整数。稍后会对这些函数进行详细介绍。

算术和优先级均与其他语言极为相似。

What about integer overflow? In C and C++ overflow of signed integers is actually undefined, and might do unknown things at runtime. In Rust, it’s defined.

Change the i32‘s to i16 to see an integer overflow, which panics (checked) in a debug build and wraps in a release build. There are other options, such as overflowing, saturating, and carrying. These are accessed with method syntax, e.g., (a * b).saturating_add(b * c).saturating_add(c * a).

事实上,编译器会检测常量表达式的溢出情况,这便是为何该示例需要单独的函数。