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

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.

主站蜘蛛池模板: 波密县| 井陉县| 旌德县| 桦甸市| 岳普湖县| 钟山县| 彰化市| 云南省| 广元市| 河曲县| 资源县| 彰化县| 卫辉市| 武邑县| 八宿县| 辽阳县| 宁明县| 巴彦县| 广汉市| 平顺县| 射阳县| 光山县| 特克斯县| 漳州市| 武乡县| 北宁市| 东乌| 洛南县| 轮台县| 独山县| 江门市| 巴彦淖尔市| 当雄县| 正阳县| 建宁县| 尼勒克县| 海晏县| 新蔡县| 苏尼特右旗| 辽阳县| 怀柔区|