Tag:

什么是惯用的Rust方法来处理大量的if-let-else代码?

我试图找出用户的当前主目录(玩具项目,学习Rust),这是我目前的代码: let mut home_dir = if let Some(path) = env::home_dir() { if let Some(path_str) = path.to_str() { path_str.to_owned() } else { panic!(“Found a home directory, but the encoding of the filename was invalid”) } } else { panic!(“Could not find home directory for current user, specify prefix manually”); }; 我来自一个高度管理的语言背景,所以也许这就是为什么这在我看来是一种反模式,但我想明白,如果我有一个更好的方式来做到这一点。 在Kotlin我会处理这种情况使用: val homeDir = env.getHomeDir()?.toString() […]

用一种expression方式创建,初始化和运行的习惯性方法

有时你有这样的事情: let mut something = Something::new(); something.set_property_a(“foo”); something.set_property_b(“bar”); let result = something.result(); 你所需要的只是结果,但现在范围被污染something 。 在Kotlin中,你可以像这样做(在其他版本中,但为了清晰起见,使用详细的): val result = Something().let { x -> x.propertyA = “foo” x.propertyB = “bar” x.result() } T.let(closure)只是运行闭T.let(closure)它的对象( Something的实例)作为参数,并返回闭包返回的任何东西。 非常轻量级和简单的概念,但非常有帮助。 在Rust里能做什么类似的事情吗? 我最近想出的是: let result = { let mut x = Something::new(); x.set_property_a(“foo”); x.set_property_b(“boo”); x.result() };