官术网_书友最值得收藏!

  • Rust Programming By Example
  • Guillaume Gomez Antoni Boucher
  • 177字
  • 2021-07-02 19:12:57

Creating functions

We had a brief introduction to functions when we saw the main function. Let's see how to create functions with parameters and a return value.

Here's how to write a function that returns the maximum of two numbers:

fn max(a: i32, b: i32) -> i32 {
    if a > b {
        a
    } else {
        b
    }
}

The parameters are between parentheses and must be explicitly typed since the type inference only infers the types of local variables. This is a good thing since this acts as a documentation. Moreover, this can prevent bugs when we change how we use the parameters or change the value that is returned. The function can be defined after it is used without any issue. The return type is after ->. When we return (), we can omit the -> and type.

The last expression in the body of a function is the value returned from the function. You don't need to use return. The return keyword is only needed when you want to return early.

主站蜘蛛池模板: 滨海县| 台中县| 招远市| 镶黄旗| 河源市| 沂南县| 丰都县| 商丘市| 寻乌县| 红安县| 含山县| 霸州市| 恭城| 五家渠市| 县级市| 光泽县| 蒙自县| 横峰县| 伊宁县| 江油市| 永登县| 茂名市| 新巴尔虎右旗| 合阳县| 顺义区| 封开县| 水城县| 高碑店市| 衡山县| 苍溪县| 丽江市| 临湘市| 洛隆县| 静乐县| 彰武县| 商都县| 河西区| 喀什市| 镇沅| 棋牌| 南宫市|