gpt4 book ai didi

rust - 如何正确处理来自Rust中maxminddb::geoip2的AddressNotFound错误?

转载 作者:行者123 更新时间:2023-12-03 11:34:48 25 4
gpt4 key购买 nike

我只有一小段代码需要修复,并且对Rust不太了解。
当我执行以下命令时,对于某些ip值将失败。

let city: geoip2::City = georeader.lookup(ip).unwrap();
let c_name = city.city
.and_then(|cy| cy.names)
.and_then(|n| n.get("en")
.map(String::from));

let loc = city.location.unwrap();
let lat = loc.latitude.unwrap();
let lon = loc.longitude.unwrap();
它失败,并显示一个AddressNotFound异常。
我试图用返回一个默认值
let city: geoip2::City = georeader.lookup(ip).unwrap_or_else(|err| geoip2::City::default(););
用它不起作用,也不能完全解决我的问题。
最后,我想捕获AddressNotFound并进行设置
let c_name = "unknown"
let loc = None
let lat = ""
let lon = ""
并在可用时使用实际值
let c_name = city.city
.and_then(|cy| cy.names)
.and_then(|n| n.get("en")
.map(String::from));
let loc = city.location.unwrap();
...
该城市何时可用。
我只是不知道如何在Rust中做这样的事情。任何人都可以为我提供有关该特定案例的快速示例或帮助吗?
更新了:
我发表评论并尝试了以下操作:
let city: std::result::Result<Option<geoip2::City>, maxminddb::MaxMindDBError> = georeader.lookup(ip);
let (c_name, lat, lon) = match city {
Ok(Some(city)) => (
city.city.and_then(|cy| cy.names)
.and_then(|n| n.get("en")
.map(String::from)),
city.location.unwrap().latitude.unwrap(),
city.location.unwrap().longitude.unwrap()
),
_ => (Some("unknown".to_owned()), 0.0_f64, 0.0_f64),
};
我知道必须找到一种在这种情况下使用多个city.location属性的方法。我目前收到此错误:
error[E0382]: use of moved value: `city.location`
--> src/main.rs:93:15
|
92 | city.location.unwrap().latitude.unwrap(),
| ------------- value moved here
93 | city.location.unwrap().longitude.unwrap()
| ^^^^^^^^^^^^^ value used here after move
|

最佳答案

也许您可以这样,尽管我是从脑海中键入内容,所以请期待它不会立即生效

let (c_name, loc, lat, lon) = match city.city {
Ok(Some(names)) => (
names.get("en").to_string(),
city.location,
<something>,
<something>,
),
_ => ("unknown", None, "", ""),
}
更新:
首先,像 CityLocation这样的实体都支持 Clone特质,因此您可以克隆然后代替移动,但是使用 .as_ref()的另一种肮脏方式是:
let city: std::result::Result<Option<geoip2::City>, maxminddb::MaxMindDBError> = georeader.lookup(ip);
let (c_name, lat, lon) = match city {
Ok(Some(city)) => (
city.city.and_then(|cy| cy.names)
.and_then(|n| n.get("en")
.map(String::from)),
city.location.as_ref().unwrap().latitude.unwrap(),
city.location.as_ref().unwrap().longitude.unwrap()
),
_ => (Some("unknown".to_owned()), 0.0_f64, 0.0_f64),
};

关于rust - 如何正确处理来自Rust中maxminddb::geoip2的AddressNotFound错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65720092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com