在 Rust 中是否有可能根据函数中定义的条件使函数返回一个对象或什么都不返回?
例如:
fn login(self, username: Username, password: Password) -> Calculator_1 {
let ch = match self.ch.send(username.to_string()).send(password.to_string()).offer() {
Left(ch) => ch,
Right(ch) => { ch.close(); return }
};
Calculator_1::new(ch)
}
我在 Rust 中使用 session 类型库,所以我希望只有在验证用户名和密码时才返回对象,这应该转到 Left
臂。如果未通过验证,则应转到 Right
臂并关闭程序。在返回或不返回方面,我真的无法做到这一点。
最佳答案
使用 Option<T>
.一个Option<T>
可以持有 Some(T)
(类型为 T
的某个值,其中 T
是泛型类型参数)或 None
(没有值(value))。
fn login(self, username: Username, password: Password) -> Option<Calculator_1> {
match self.ch.send(username.to_string()).send(password.to_string()).offer() {
Left(ch) => Some(Calculator_1::new(ch)),
Right(ch) => { ch.close(); None }
}
}
有关详细信息,请阅读 Error Handling Rust 编程语言 中的章节。
关于rust - 是否可以返回或什么都不退?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39260533/