Skip to content
On this page

函数4: exercises/functions/functions4.rs

题目

rust
// functions4.rs
//
// This store is having a sale where if the price is an even number, you get 10
// Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. (Don't worry
// about the function bodies themselves, we're only interested in the signatures
// for now. If anything, this is a good way to peek ahead to future exercises!)
//
// Execute `rustlings hint functions4` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

fn main() {
    let original_price = 51;
    println!("Your sale price is {}", sale_price(original_price));
}

fn sale_price(price: i32) -> {
    if is_even(price) {
        price - 10
    } else {
        price - 3
    }
}

fn is_even(num: i32) -> bool {
    num % 2 == 0
}

题目说,有一家商店在进行促销,如果价格是偶数,那么你就得到10 Rustbucks折扣,但是如果是奇数,就会有3 Rustbucks的折扣。

题目解析

首先,我们先来看代码逻辑:

  • main函数定义了一个原始价格original_price,然后需要调用sale_price(original_price)函数来获取销售价格
  • sale_price函数通过is_even函数来判断原价是否是偶数
  • 如果是偶数,就折扣10
  • 如果是奇数,就折扣3

逻辑大体看起来没有问题,我们再看编译器错误信息如下:

txt
⚠️  Compiling of exercises/functions/functions4.rs failed! Please try again. Here's the output:
error: expected type, found `{`
  --> exercises/functions/functions4.rs:18:30
   |
18 | fn sale_price(price: i32) -> {
   |                              ^ expected type

error: aborting due to previous error

编译器信息提示我们:

  • 缺少返回值类型

此处我们根据参数price: i32可以推导出返回值应该也是i32类型,所以我们直接补充返回值类型:

rust
fn main() {
    let original_price = 51;
    println!("Your sale price is {}", sale_price(original_price));
}

fn sale_price(price: i32) -> { 
fn sale_price(price: i32) -> i32 { 
    if is_even(price) {
        price - 10
    } else {
        price - 3
    }
}

fn is_even(num: i32) -> bool {
    num % 2 == 0
}

编译通过。

笔记

  • 函数可以有返回值
  • 我们不对返回值命名,但要在箭头(->)后声明它的类型
  • 函数的返回值等同于函数体最后一个表达式的值,此时不需要return,末尾也不需要加分号;
  • 使用 return 关键字和指定值,可从函数中提前返回,此时末尾需要加分号;

参考资料

Powered by VitePress