我刚接触Rust,所以我不知道如何修复这个错误.我知道没有导入库,但是在cargo.toml文件中,所有的库都是导入的. Sus_fns.rs:

use std::fs;
use rand::Rng;
use regex::Regex;

pub fn generate_memes_text(chat_id: &str) -> String {
    let filename = format!("../all_databases/stytsko_folder_id_{}_v/stytsko_db_mod=one-line_id_{}_v.txt", chat_id, chat_id);
    let _contents = fs::read_to_string(&filename).expect("Unable to read file");

    fn extract_words_from_buffer(buffer: &str) -> Vec<&str> {
        let re = Regex::new(r"[\s\n]+").unwrap();
        re.split(buffer.trim()).collect()
    }

    fn build_markov_chain<'a>(words: &'a [&'a str]) -> std::collections::HashMap<&'a str, Vec<&'a str>> {
        let mut markov_chain = std::collections::HashMap::new();

        for i in 0..words.len()-1 {
            let current_word = words[i];
            let next_word = words[i+1];

            markov_chain.entry(current_word).or_insert(Vec::new()).push(next_word);
        }

        markov_chain
    }

    fn generate_markov_expression(markov_chain: &std::collections::HashMap<&str, Vec<&str>>, num_words: usize) -> String {
        let mut expression = String::new();
        let mut current_word = get_random_word(markov_chain.keys().cloned().collect());

        let mut num_words_remaining = num_words;
        while num_words_remaining > 0 {
            expression.push_str(current_word);
            expression.push(' ');

            let empty_vec = Vec::new();
            let next_words = markov_chain.get(current_word).unwrap_or(&empty_vec).to_vec();
            if next_words.is_empty() {
                break;
            }

            current_word = get_random_word(next_words.iter().cloned().collect());
            num_words_remaining -= 1;
        }

        expression.trim().to_string()
    }

    fn get_random_word(words: Vec<&str>) -> &str {
        let mut rng = rand::thread_rng();
        let random_index = rng.gen_range(0..words.len());
        words[random_index]
    }

    fn generate_message_from_file(filename: &str, num_words: usize) -> String {
        let contents = fs::read_to_string(filename).expect("Unable to read file");
        let words = extract_words_from_buffer(&contents);

        let expression = if words.len() > num_words {
            let markov_chain = build_markov_chain(&words);
            generate_markov_expression(&markov_chain, num_words)
        } else if words.len() == num_words {
            words.join(" ")
        } else {
            words[..words.len()-1].join(" ")
        };

        expression
    }

    let num_words = rand::thread_rng().gen_range(1..=5);
    let selected_words = generate_message_from_file(&filename.clone(), num_words);

    selected_words
}

Lib.Rs:

mod sys_fns;

#[no_mangle]
pub extern "C" fn generate_memes_text(chat_id: *const i8) -> *mut i8 {
    use std::ffi::CString;
    use std::ffi::CStr;
    use std::str;

    let chat_id_str = unsafe { CStr::from_ptr(chat_id).to_bytes() };
    let chat_id_string = str::from_utf8(chat_id_str).unwrap();
    let selected_words = sys_fns::generate_memes_text(chat_id_string);
    let result = CString::new(selected_words).unwrap().into_raw();

    result
}

货运量:

[package]
name = "myproject"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8"
regex = "1.4"

错误:

C:\MeFolder\testing python with rust>rustc --crate-type cdylib myproject/src/lib.rs
error[E0432]: unresolved import `rand`
 --> myproject/src\sys_fns.rs:2:5
  |
2 | use rand::Rng;
  |     ^^^^ maybe a missing crate `rand`?
  |
  = help: consider adding `extern crate rand` to use the `rand` crate

error[E0432]: unresolved import `regex`
 --> myproject/src\sys_fns.rs:3:5
  |
3 | use regex::Regex;
  |     ^^^^^ maybe a missing crate `regex`?
  |
  = help: consider adding `extern crate regex` to use the `regex` crate

error[E0433]: failed to resolve: use of undeclared crate or module `rand`
  --> myproject/src\sys_fns.rs:71:21
   |
71 |     let num_words = rand::thread_rng().gen_range(1..=5);
   |                     ^^^^ use of undeclared crate or module `rand`

error[E0433]: failed to resolve: use of undeclared crate or module `rand`
  --> myproject/src\sys_fns.rs:50:23
   |
50 |         let mut rng = rand::thread_rng();
   |                       ^^^^ use of undeclared crate or module `rand`

错误: aborting due to 4 previous errors

Some errors have detailed explanations: E0432, E0433.
For more information about an error, try `rustc --explain E0432`.

Sys_fns.rs中的代码不是我写的.它被Pplexity.ai从Python翻译成Rust

我try 更新Cargo,编写命令Cargo UPDATE、Cargo Build(在cargo.toml中写入所有库之后),但错误仍然是一样的.此外,我还try 通过Cargo Build--Release--lib完成此操作,但DLL文件并未出现.

推荐答案

除非您真的知道自己在做什么,否则您应该直接调用never调用rustc.一定要用cargo.

如果你想要cdylib分,在Cargo.toml中这样说:

[package]
name = "myproject"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
rand = "0.8"
regex = "1.4"

然后使用cargo build构建包,并判断target/debug文件夹(或cargo build --releasetarget/release文件夹)中的输出文件(.dll.so.dylib).

Rust相关问答推荐

泛型属性比较

trait声明中的生命周期参数

为什么`Vec i64`的和不知道是`Option i64`?

MPSC频道在接收器处阻塞

使用Box优化可选的已知长度数组的内存分配

如何循环遍历0..V.len()-1何时v可能为空?

如何将映射反序列化为具有与键匹配的字段的定制 struct 的向量?

铁 rust 中双倍或更多换行符的更好练习?

为什么&;mut buf[0..buf.len()]会触发一个可变/不可变的borrow 错误?

方法可以被误认为是标准特性方法

如何基于常量在Rust中跳过一个测试

如何在Rust中使用Serde创建一个自定义的反序列化器来处理带有内部标记的枚举

注释闭包参数强调使用高阶排定特征界限

为什么 Rust 的临时值有时有参考性有时没有?

为什么数组不像向量那样在 for 块之后移动?

在运行时在 Rust 中加载字体

为什么我可以同时传递可变和不可变引用?

如何在 Rust Polars 中可靠地连接 LazyFrames

你能告诉我如何在 Rust 中使用定时器吗?

您不能borrow 对只读值的可变引用