2016-12-25 13 views
8

從閱讀this thread,它看起來有可能使用shebang運行Rust *。如何直接在Unix系統上執行Rust代碼? (使用shebang)

#!/usr/bin/env rustc 

fn main() { 
    println!("Hello World!"); 
} 

使這個可執行文件和運行編譯,但不運行代碼。

chmod +x hello_world.rs 
./hello_world.rs 

但是,這隻能編碼到hello_world

可以*.rs文件直接執行,類似於一個shell腳本?


*此引用rustx,我看着這一點,但它的一個bash腳本編譯每次(無緩存)腳本,絕不會取消從臨時目錄中的文件,雖然這可以改善。它也有不能使用木箱的重大限制。

+1

https://github.com/killerswan/rustx? –

回答

10

cargo-script。這也讓你使用依賴關係。

通過cargo install cargo-script安裝cargo-script後,您可以像這樣創建腳本文件(hello.rs):

#!/usr/bin/env run-cargo-script 

fn main() { 
    println!("Hello World!"); 
} 

要執行它,你需要:

$ chmod +x hello.rs 
$ ./hello.rs 
    Compiling hello v0.1.0 (file://~/.cargo/.cargo/script-cache/file-hello-d746fc676c0590b) 
    Finished release [optimized] target(s) in 0.80 secs 
Hello World! 

要使用板條箱來自crates.io,請參閱上面鏈接的自述文件中的教程。

1

這似乎工作:

#!/bin/sh 
//usr/bin/env rustc $0 -o a.out && ./a.out && rm ./a.out ; exit 

fn main() { 
    println!("Hello World!"); 
} 
+1

不適合任何需要箱子的東西。 – Shepmaster

+2

如果運行'a.out'返回一個非零退出代碼,'&&'將無法刪除'a.out'。 – ideasman42

相關問題