什么是惯用的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() ?: throw RuntimeException(...)
方式?
在Rust中的宏需要我使用返回一个Result
的函数,我相信main()
不会,而且它也不一定是有意义的。 任何指针?