熟悉Python的小伙伴们一定用过 ipython
,数据行业的从业者也一定用过 jupyter
,交互式执行,及时反馈,快速验证想法、记录文档。Rust 作为一种编译型语言,是否有这样好用的工具呢?
下面就有请我们今天的主角 evcxr`` 登场。evcxr
是一个 Google 开源项目,为我们提供了类似Python那样的交互式Rust编程体验,我们可以使用它快速的执行我们的代码片段,及时反馈执行结果,而不是每次都要创建一个工程,这个在Rust 入门学习阶段很有用。evcxr
提供了 REPL
和Jupyter
两种交互编程模式,对应 Python 的终端交互模式和 Jupyter 笔记本。
REPL
要想 REPL 式的执行我们的 Rust 代码片段很简单,安装 evcxr_repl
即可:
cargo install evcxr_repl
然后我们就可以愉快的交互式编程了:
$ evcxr
Welcome to evcxr. For help, type :help
>> :help
:clear Clear all state, keeping compilation cache
:dep Add dependency. e.g. :dep regex = "1.0"
:efmt Set the formatter for errors returned by ?
:explain Print explanation of last error
:fmt Set output formatter (default: {:?})
:help Print command help
:internal_debug Toggle various internal debugging code
:last_compile_dir Print the directory in which we last compiled
:last_error_json Print the last compilation error as JSON (for debugging)
:linker Set/print linker. Supported: system, lld, mold
:load_config Reloads startup configuration files. Accepts optional flag `--quiet` to suppress logging.
:offline Set offline mode when invoking cargo
:opt Set optimization level (0/1/2)
:preserve_vars_on_panic Try to keep vars on panic (0/1)
:quit Quit evaluation and exit
:sccache Set whether to use sccache (0/1).
:time_passes Toggle printing of rustc pass times (requires nightly)
:timing Toggle printing of how long evaluations take
:toolchain Set which toolchain to use (e.g. nightly)
:vars List bound variables and their types
:version Print Evcxr version
注意 :dep
可以引入第三方依赖包,例如::dep regex = "1.0"
。
看 《Rust 实战》中的一个例子:
$ evcxr
Welcome to evcxr. For help, type :help
>> :dep num
>> use num::complex::Complex;
>> let a = Complex { re: 2.1, im: -1.2 };
>> let b = Complex::new(11.1, 22.22);
>> let result = a + b;
>> println!("{} + {}i", result.re, result.im);
13.2 + 21.02i
>> :vars
b: Complex<f64>
result: Complex<f64>
a: Complex<f64>
Jupyter
REPL 模式下我们编写的内容并不能很好的保存起来,不利于总结输出。evcxr
给我们提供了 Jupyter
模式。首先确保本机安装的有 Python 解释器,并且安装的有 jupyter
,这里推荐更好用的 jupyterlab
,没有的话自行安装:
pip install jupyterlab
然后安装 evcxr_jupyter
:
cargo install evcxr_jupyter
接着运行如下命令,以便向Jupyter注册Rust内核:
evcxr_jupyter --install
最后运行如下命令,就可以进入笔记本环境了:
jupyter lab
点击 NoteBook 中的 Rust,就可以创建一个Rust交互执行笔记本,然后我们就可以边学边练边记录了:
习惯使用 IDE 的话,我们也可以在 VSCode、PyCharm 中打开或者新建我们的 Rust 笔记本文件:
简单演示介绍就到这里,更多细节可以看官方文档,希望小伙伴们通过 evcxr
能更快速的上手 Rust 语言。