我正在尝试使用readline驱动的命令提示符创建一个程序。
我正在使用this crate。
readline = "0.0.11"
这是存储库中的示例。 (链接到存储库位于包装箱的页面上。)
#![cfg(not(test))]
extern crate readline;
use readline::readline;
use std::ffi::CString;
use std::io::Write;
use std::io;
fn main() {
let prompt = CString::new("user> ").unwrap();
let mut stdout = io::stdout();
while let Ok(s) = readline(&prompt) {
stdout.write_all(s.to_bytes()).unwrap();
stdout.write_all(b"\n").unwrap();
}
stdout.write_all(b"\n").unwrap();
}
我正在尝试将s
从readline::common::ReadlineBytes
转换为std::string::String
,因此我可以match
就这样。
while let Ok(s) = readline(&prompt){
let command = str::from_utf8(&s.to_bytes()).unwrap();
match command {
"exit" => std::process::exit,
"again" => break,
_ => println!("error")
}
println!("{}", command);
}
但我一直收到这个错误:
main.rs:18:9: 22:10 error: match arms have incompatible types:
expected `fn(i32) -> ! {std::process::exit}`,
found `()`
(expected fn item,
found ()) [E0308]
main.rs:18 match command {
main.rs:19 "exit" => std::process::exit,
main.rs:20 "again" => break,
main.rs:21 _ => println!("error")
main.rs:22 }
note: in expansion of while let expansion
main.rs:16:5: 24:6 note: expansion site
main.rs:18:9: 22:10 help: run `rustc --explain E0308` to see a detailed explanation
main.rs:21:18: 21:35 note: match arm with an incompatible type
main.rs:21 _ => println!("error")
^~~~~~~~~~~~~~~~~
note: in expansion of while let expansion
main.rs:16:5: 24:6 note: expansion site
error: aborting due to previous error
答案 0 :(得分:2)
匹配武器都必须返回相同的类型。再次查看您的错误消息:
main.rs:18:9: 22:10 error: match arms have incompatible types:
expected `fn(i32) -> ! {std::process::exit}`,
found `()`
(expected fn item,
found ()) [E0308]
你的一个匹配臂正在返回()
,另一个正在返回类型fn(i32) -> ! {std::process::exit}
- 一个函数。
看看你的代码:
"exit" => std::process::exit,
您不是致电 exit
,您只是返回对它的引用。