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

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!

主站蜘蛛池模板: 新营市| 木里| 绍兴县| 武鸣县| 巩义市| 苍山县| 芮城县| 双柏县| 荥阳市| 托克逊县| 武功县| 澄迈县| 洮南市| 广东省| 保亭| 长宁区| 乃东县| 天台县| 宁南县| 五寨县| 霍州市| 林州市| 商南县| 收藏| 乾安县| 宝山区| 襄汾县| 鄂伦春自治旗| 丽江市| 合作市| 龙游县| 天津市| 平凉市| 紫阳县| 许昌县| 惠来县| 石渠县| 阳山县| 中牟县| 鹿泉市| 荣昌县|