算术

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

fn main() {
    println!("result: {}", interproduct(120, 100, 248));
}
This slide should take about 3 minutes.

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

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

整数溢出是什么样的?在 C 和 C++ 中,有符号 整数溢出实际上是未定义的,可能会在不同平台或编译器上执行不同的操作。在 Rust 中,整数溢出具有明确定义。

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).

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