gpt4 book ai didi

readline - 将 readline 接口(interface)到 Rust

转载 作者:行者123 更新时间:2023-11-29 07:58:24 29 4
gpt4 key购买 nike

我尝试做 this tutorial在 Rust 中,到目前为止,我在将 C 库连接到 Rust 时遇到了很多问题。

C 等效代码:

#include <stdio.h>
#include <stdlib.h>

#include <editline/readline.h>
#include <editline/history.h>

int main(int argc, char** argv) {

/* Print Version and Exit Information */
puts("Lispy Version 0.0.0.0.1");
puts("Press Ctrl+c to Exit\n");

/* In a never ending loop */
while (1) {

/* Output our prompt and get input */
char* input = readline("lispy> ");

/* Add input to history */
add_history(input);

/* Echo input back to user */
printf("No you're a %s\n", input);

/* Free retrived input */
free(input);

}

return 0;
}

到目前为止我得到了这个:

extern crate libc;

use std::c_str;

#[link(name = "readline")]
extern {
fn readline (p: *const libc::c_char) -> *const libc::c_char;
}

fn rust_readline (prompt: &str) -> Option<Box<str>> {
let cprmt = prompt.to_c_str();
cprmt.with_ref(|c_buf| {
unsafe {
let ret = c_str::CString::new (readline (c_buf), true);
ret.as_str().map(|ret| ret.to_owned())
}
})
}

fn main() {
println!("Lispy Version 0.0.1");
println!("Press Ctrl+c to Exit.\n");

// I want to have "history" in Linux of this:
//
// loop {
// print!("lispy> ");
// let input = io::stdin().read_line().unwrap();
// print!("No you're a {}", input);
// }

loop {
let val = rust_readline ("lispy> ");
match val {
None => { break }
_ => {
let input = val.unwrap();
println!("No you're a {}", input);
}
}
}
}

特别是,我对 rust_readline 函数有问题,我不太明白里面在做什么。

最佳答案

编辑 Cargo.toml,放入:

[dependencies.readline]

git = "https://github.com/shaleh/rust-readline"

代码更正:

extern crate readline;

fn main() {
println!("Lispy Version 0.0.1");
println!("Press Ctrl+c to Exit.\n");

loop {
let input = readline::readline("lispy> ").unwrap();
readline::add_history(input.as_str());
println!("No you're a {}", input);
}
}

Happy Linping :-) .

关于readline - 将 readline 接口(interface)到 Rust,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26205695/

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