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

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!

主站蜘蛛池模板: 龙口市| 叙永县| 大连市| 信丰县| 台北市| 西平县| 恭城| 镇江市| 冷水江市| 宁城县| 娄烦县| 牡丹江市| 思南县| 西林县| 高密市| 垣曲县| 科尔| 阿坝县| 公主岭市| 陆丰市| 嘉禾县| 武城县| 华安县| 保山市| 呼玛县| 吴桥县| 白朗县| 永康市| 保山市| 武隆县| 全州县| 蓝田县| 西昌市| 凉城县| 峨山| 昆明市| 漳州市| 扶绥县| 永德县| 黄骅市| 新泰市|