gpt4 book ai didi

rust - 无法从 Rocket 路由返回字符串

转载 作者:行者123 更新时间:2023-11-29 08:25:16 26 4
gpt4 key购买 nike

我正在尝试创建一个将字符串返回给客户端的 Rocket 路由,但我无法让它工作。到目前为止,这就是我所拥有的:

#![feature(plugin)]
#![plugin(rocket_codegen)]
#[macro_use]

extern crate serde_derive;
extern crate toml;
extern crate rocket;

mod utilities;
mod pipeline_config;
mod assets;

use std::path::PathBuf;

#[get("/resources/<path..>")]
fn get_resource(path: PathBuf) -> Result<String, ()> {
if let Some(page_path) = path.to_str() {
match assets::get(&format!("{}/{}", "resources", page_path)) {
Ok(page) => Ok(utf8_to_string(page)),
Err(e) => Err(()),
}
}
Err(())
}

fn main() {
let rocket_obj = rocket::ignite();
rocket_obj.mount("/", routes![get_resource]).launch();
}

pub fn utf8_to_string(bytes: &[u8]) -> String {
let vector: Vec<u8> = Vec::from(bytes);
String::from_utf8(vector).unwrap()
}

看起来应该可以,但它给了我一个错误 expected (), found enum std::result::Result:

error[E0308]: mismatched types
--> src/main.rs:18:9
|
18 | / match assets::get(&format!("{}/{}", "resources", page_path)) {
19 | | Ok(page) => Ok(utf8_to_string(page)),
20 | | Err(e) => Err(()),
21 | | }
| | ^- help: try adding a semicolon: `;`
| |_________|
| expected (), found enum `std::result::Result`
|
= note: expected type `()`
found type `std::result::Result<std::string::String, ()>`

这对我来说毫无意义,因为我要返回一个带有 StringResult

最佳答案

当您使用函数式风格时,将一个函数视为一个表达式。您的函数 get_resource 有两个并排放置的表达式。编译器什么都不懂。您必须将备选方案放在 else 分支中,:如果我能得到一些路径,请执行此操作;否则这是一个错误:

fn get_resource(path: PathBuf) -> Result<String, ()> { 
if let Some(page_path) = path.to_str() {
match assets::get(&format!("{}/{}", "resources", page_path)) {
Ok(page) => Ok(utf8_to_string(page)),
Err(e) => Err(()),
}
} else {
Err(())
}
}

换句话说,您可以将函数视为逻辑树,其中每个 ifmatch block 都是一组分支。该程序将根据输入遵循此树中的路径:因此您必须只有一个树干,否则它没有意义。

关于rust - 无法从 Rocket 路由返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44795305/

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