可以说我想为HTTP API写一个小的客户端。它具有返回汽车列表的资源:
GET /cars
它还接受两个可选的查询参数color
和manufacturer
,因此我可以查询特定的汽车,例如:
GET /cars?color=black
GET /cars?manufacturer=BMW
GET /cars?color=green&manufacturer=VW
如何在Rust中适当地公开这些资源?由于Rust不支持重载,因此定义多个函数似乎是通常的方法,例如:
fn get_cars() -> Cars
fn get_cars_by_color(color: Color) -> Cars
fn get_cars_by_manufacturer(manufacturer: Manufacturer) -> Cars
fn get_cars_by_manufacturer_and_color(manufacturer: Manufacturer, color: Color) -> Cars
但是,当您拥有多个参数时,这显然将无法缩放。
另一种方法是使用结构:
struct Parameters {
color: Option<Color>,
manufacturer: Option<Manufacturer>
}
fn get_cars(params: Parameters) -> Cars
这具有相同的缩放问题,必须在创建时设置每个struct字段(即使其值只是None
)。
我想我可以接受HashMap<String, String>
,但这听起来也不是很好。所以我的问题是,在Rust中执行此操作的正确/最佳方法是什么?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句