2

我的程序在我的本地机器上按预期工作。它以 Emacs “Spook” 游戏 (Mx spook) 的方式从文本文件中打印随机行。文本文件位于src/spook.lines.

C:\Users\datan>spooks
domestic Eiffel Tower Euzkadi Ta Askatasuna Euzkadi Ta Askatasuna minefield
C:\Users\datan>spooks
Uzi White House secret Sivi Vukovi divers
C:\Users\datan>spooks
Hizb-i-Islami smallpox US Airways SWAT plague
C:\Users\datan>

但是如果我将它作为 crate 发布并安装它,则找不到文本文件(因为src/spook.lines如果程序是从 crates.io 安装的,则它不在其中):

C:\Users\datan>docker run -it rust bash
Unable to find image 'rust:latest' locally
latest: Pulling from library/rust
16ea0e8c8879: Pull complete
50024b0106d5: Pull complete
ff95660c6937: Pull complete
9c7d0e5c0bc2: Pull complete
29c4fb388fdf: Pull complete
ee0ab7fd0ac4: Pull complete
Digest: sha256:d8e2b124d6f4fcdf977bf7e6cfbda87fa5061b0c1933742699ee5131444217c9
Status: Downloaded newer image for rust:latest
root@137111b4d94c:/# cargo install spooks
    Updating crates.io index
  Downloaded spooks v0.1.0
  Downloaded 1 crate (19.0 KB) in 1.60s
  Installing spooks v0.1.0
  Downloaded getopts v0.2.21
  Downloaded rand v0.7.2
  Downloaded rand_chacha v0.2.1
  Downloaded easy_reader v0.5.0
  Downloaded getrandom v0.1.13
  Downloaded rand_core v0.5.1
  Downloaded unicode-width v0.1.7
  Downloaded libc v0.2.66
  Downloaded c2-chacha v0.2.3
  Downloaded fnv v1.0.6
  Downloaded cfg-if v0.1.10
  Downloaded ppv-lite86 v0.2.6
   Compiling libc v0.2.66
   Compiling getrandom v0.1.13
   Compiling cfg-if v0.1.10
   Compiling ppv-lite86 v0.2.6
   Compiling fnv v1.0.6
   Compiling unicode-width v0.1.7
   Compiling getopts v0.2.21
   Compiling c2-chacha v0.2.3
   Compiling rand_core v0.5.1
   Compiling rand_chacha v0.2.1
   Compiling rand v0.7.2
   Compiling easy_reader v0.5.0
   Compiling spooks v0.1.0
    Finished release [optimized] target(s) in 22.15s
  Installing /usr/local/cargo/bin/spooks
   Installed package `spooks v0.1.0` (executable `spooks`)
root@137111b4d94c:/# spooks
(no output because src/spook.lines is not there)

我包含文件的方式是:

let file = File::open("src/spook.lines")?;

为什么我不能只告诉货物/板条箱包装包含文本文件?首选方式是什么?我的意思是即使我将文件包含在某个目录中,它也不会在PATH执行中,因为程序可能从任何地方运行。

4

1 回答 1

0

您可以使用include_str!宏。

fn main() {
    let my_str = include_str!("spanish.in");
    assert_eq!(my_str, "adiós\n");
    print!("{}", my_str);
}

https://doc.rust-lang.org/std/macro.include_str.html

于 2019-12-18T08:06:36.673 回答