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

Shadowing

Instead of changing variable properties, it's often more readable to overwrite a variable with a different value (for example, a changed copy of the original). This technique is called shadowing.

Typically, this is used to reuse a variable name, even though the actual value has changed, to work in the current situation. This snippet sanitizes String and, by using the same name throughout the function, it's always clear that it's the input parameter that is changed:

fn sanitize(s: String) -> String {
let s = s.trim();
let s = s.replace(" ", "_");
s
}

While this is akin to changing the value of a variable, shadowing does not replace mutability, especially when it's less costly to actually change properties of that variable; Rust has a specific design pattern for that!

主站蜘蛛池模板: 若羌县| 嘉黎县| 陵水| 济宁市| 巴南区| 乾安县| 外汇| 肇州县| 铁岭县| 马边| 晴隆县| 中卫市| 宾阳县| 阿巴嘎旗| 泾川县| 台前县| 诸暨市| 滦平县| 剑阁县| 定襄县| 聊城市| 乌拉特后旗| 丘北县| 平山县| 缙云县| 卓资县| 安化县| 广元市| 英超| 广宗县| 慈溪市| 鹤峰县| 河池市| 东乡| 呈贡县| 江华| 明星| 宽城| 丰原市| 久治县| 东明县|