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

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!

主站蜘蛛池模板: 定日县| 固原市| 甘谷县| 若尔盖县| 景洪市| 正镶白旗| 手游| 禄丰县| 涪陵区| 正宁县| 沙河市| 德化县| 东乌| 榆树市| 鸡西市| 沙雅县| 厦门市| 威远县| 都江堰市| 临武县| 洛宁县| 大兴区| 若羌县| 九寨沟县| 巴楚县| 香格里拉县| 龙井市| 原阳县| 大余县| 沛县| 永顺县| 泾阳县| 鄢陵县| 木兰县| 迭部县| 长宁县| 偃师市| 洛宁县| 湘西| 桑植县| 搜索|