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

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!

主站蜘蛛池模板: 台安县| 汉川市| 泗洪县| 延吉市| 永福县| 三江| 台州市| 增城市| 三台县| 尼勒克县| 新郑市| 嘉义县| 图们市| 乾安县| 七台河市| 上饶市| 隆化县| 麦盖提县| 皮山县| 巍山| 峨边| 大同县| 宜兰市| 泽库县| 民勤县| 班玛县| 云浮市| 临颍县| 灵石县| 宜州市| 榆社县| 大丰市| 任丘市| 黄龙县| 雅江县| 沧州市| 莱阳市| 清涧县| 盘山县| 吉首市| 庆城县|