2016-12-25 66 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

相关问题