将 Vim 设置为你的 Rust IDE

Vim 文本编辑器是开发 Rust 应用程序的绝佳环境。
111 位读者喜欢这篇文章。
Ferris the crab under the sea, unofficial logo for Rust programming language

Opensource.com

Rust 编程语言旨在实现系统编程,它具有安全的并发性和高内存性能,并且让 C++ 开发者感到熟悉。它也是 Stack Overflow 2019 年开发者调查中最受欢迎的编程语言之一。

文本编辑器和集成开发环境 (IDE) 工具使编写 Rust 代码更加容易和快捷。 有许多编辑器可供选择,但我认为 Vim 编辑器 非常适合作为 Rust IDE。 在本文中,我将解释如何设置 Vim 以进行 Rust 应用程序开发。

安装 Vim

Vim 是 Linux 和 Unix 中最常用的命令行文本编辑器之一。 最新版本(截至本文撰写时)是 8.2,它在您如何使用它方面提供了前所未有的灵活性。

Vim 的下载页面 提供了多种选项,可以使用二进制文件或软件包安装它。 例如,如果您使用 macOS,则可以安装 MacVim 项目,然后通过安装 Vim 插件来扩展 Vim 的功能。

要设置 Rust 进行开发,请下载 Rustup,这是一个方便的 Rust 安装程序实用程序,然后在您的终端中运行以下命令(如果您使用 macOS、Linux 或任何其他类 Unix 操作系统)

$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

从交互式提示中选择一个安装选项。 然后您将看到如下输出

stable installed - rustc 1.43.1 (8d69840ab 2020-05-04)


Rust is installed now. Great!

To get started you need Cargo's bin directory ($HOME/.cargo/bin) in your PATH
environment variable. Next time you log in this will be done
automatically.

To configure your current shell run source $HOME/.cargo/env

语法高亮

Vim 允许您通过在 .vimrc 文件中定义运行时配置。 要启用语法高亮,请打开您的 .vimrc 文件(如果不存在则创建一个)

$ vim ~/.vimrc

.vimrc 文件中添加以下内容并保存

filetype plugin indent on
syntax on

第一行一次性打开检测、插件和缩进配置。 第二行启用语法高亮。 这些功能将帮助您管理 Rust 中的开发者工作流程。 在 Vim 的帮助文件中了解更多信息。

在 Vim 中创建 Rust 应用程序

要使用 Vim 创建一个新的 Rust HelloWorld 应用程序 (hello.rs),请输入

$ vim hello.rs

输入以下 Rust 代码以在控制台中打印 Hello World!

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

它应该看起来像这样

这是没有语法高亮的样子

您是否注意到 Vim 如何自动缩进和组织代码? 这是因为您在 .vimrc 文件中输入的第一行。

做得好! 接下来,您将使用 Rust 的包管理器 Cargo 构建此应用程序。

Cargo 集成

Cargo 使创建应用程序变得更容易。 要了解如何操作,请创建一个基于 Cargo 的 HelloWorld 应用程序。 如果您的 Linux 或 macOS 系统上尚未安装 Cargo,请输入

$ curl https://sh.rustup.rs -sSf | sh

然后使用 Cargo 创建一个包

$ cargo new my_hello_world

如果您查看目录结构,您将看到 Cargo 自动生成了一些源代码和目录。 如果您安装了 tree,请运行它以查看目录结构

$ tree my_hello_world 
my_hello_world
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files

在 Vim 中打开 main.rs 源代码文件

$ vim my_hello_world/src/main.rs

代码与您在上面手动创建的 HelloWorld 示例中的代码相同。 将 World 替换为 Rust with Vim

 fn main() {
      println!("Hello, Rust with Vim");
 }

使用 :wq 保存更改并退出 Vim。

编译您的应用程序

现在您可以使用 cargo build 编译您的第一个 Rust 应用程序

$ cd my_hello_world 
$ cargo build

您的终端输出将与此类似

   Compiling my_hello_world v0.1.0 (/Users/danieloh/cloud-native-app-dev/rust/my_hello_world)

    Finished dev [unoptimized + debuginfo] target(s) in 0.60s

您可能会看到一条警告消息,因为您重用了示例包名称 my_hello_world,但您现在可以忽略它。

运行应用程序

$ target/debug/my_hello_world
Hello, Rust with Vim!

您也可以使用 cargo run 一次性构建和运行应用程序

$ cargo run
  
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/my_hello_world`
Hello, Rust with Vim!!

恭喜! 您在本地机器上为 Rust IDE 设置了 Vim 编辑器,开发了您的第一个 Rust 应用程序,并使用 Cargo 包管理器工具构建、测试和运行了它。 如果您想了解其他 Cargo 命令,请运行 cargo help

接下来阅读什么
标签
danieloh
技术营销,开发者倡导者,CNCF 大使,公开演讲者,出版作家,Quarkus,红帽运行时

2 条评论

为了构建而离开 vim 是一个麻烦事。

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 许可。
© . All rights reserved.