Document
Rust with Visual Studio Code

Rust with Visual Studio Code

Rust in Visual Studio Code Rust is a powerful programming language, often used for systems programming where performance and correctness are high pri

Related articles

Cloud Classification 国内可用、提供永久免费计划的VPN #1 SoundCloud Downloader to MP3 Converter Online 2024 6 VPN Terbaik untuk YouTube (2024) How to Access 1337x And Watch Movie If It Is Blocked

Rust in Visual Studio Code

Rust is a powerful programming language, often used for systems programming where performance and correctness are high priorities. If you are new to Rust and want to learn more, The Rust Programming Language online book is a great place to start. This topic goes into detail about setting up and using Rust within Visual Studio Code, with the rust-analyzer extension.

note :There is also another popular rust extension in the VS Code Marketplace ( extension id :rust-lang.rust ) but this extension is deprecate and rust – analyzer is the recommend VS Code Rust extension by rust-lang.org .

Installation

1 . Install Rust

First you will need to have the Rust toolset installed on your machine. Rust is installed via the rustup installer, which supports installation on window, macOS, and Linux. Follow the rustup installation guidance for your platform, taking care to install any extra tools required to build and run Rust programs.

Note:As with installing any new toolset on your machine, you’ll want to make sure to restart your terminal/Command Prompt and VS Code instances to use the updated toolset location in your platform’s PATH variable.

2 . install the rust – analyzer extension

You can find and install the rust-analyzer extension from within VS Code via the Extensions view (⇧⌘X ( window , LinuxCtrl+Shift+X)) and search for ‘ rust – analyzer ‘ . You is install should install the Release Version .

Rust with Visual Studio Code

We is discuss ‘ll discuss many of rust – analyzer feature in this topic but you can also refer to the extension ‘s documentation at https://rust-analyzer.github.io .

check your installation

After installing Rust, you can check that everything is installed correctly by opening a new terminal/Command Prompt, and typing:

rustc --version

which will output the version of the Rust compiler. If you want more details, you can add the --verbose argument. If you run into problems, you can consult the Rust installation guide.

You can keep your Rust installation up to date with the latest version by running:

rustup update

There are new stable versions of Rust published every 6 weeks so this is a good habit.

Local Rust documentation

When you install Rust, you also get the full Rust documentation set locally installed on your machine, which you can review by typing rustup doc. The Rust documentation, including The Rust Programming Language and The cargo Book, will open in your local browser so you can continue your Rust journey while offline.

Hello World

cargo

When you install Rust with rustup, the toolset includes the rustc compiler, the rustfmt source codeformatter, and the clippy Rust linter. You also get cargo, the Rust package manager, to help download Rust dependencies and build and run Rust programs. You’ll find that you end up using cargo for just about everything when working with Rust.

cargo new

A good way to create your first Rust program is to use cargo to scaffold a new project by typing cargo new. This will create a simple Hello World program along with a default cargo.toml dependency file . You is pass passcargo new the folder where you ‘d like to create the project .

Let’s create Hello World. Navigate to a folder where you’d like to create your project and type:

cargo new hello_world

To open your new project in VS Code , navigate into the new folder and launch VS Code viacode.:

cd hello_world
code.

note :enable Workspace Trust for the new folder as you are the author . You is enable can enable Workspace Trust for your entire project folder parent to avoid being prompt when you create new project by check the option to trust the author of all the file in parent folder ‘ my_project ` .

cargo new creates a simple Hello World project with a main.r source codefile and cargo.toml cargo manifest file.

src\
    main.r
.gitignore
cargo.toml

main.r has the program’s entry function main ( ) and print ” Hello , world ! ” to the console usingprintln!.

fn main() {
    println!("Hello, world!") ;
}

This simple Hello World program doesn’t have any dependencies but you would add Rust package (crate) references under [dependencies].

cargo build

cargo can be used to build your Rust project. Open a new VS Code integrated terminal (⌃⇧` ( window , LinuxCtrl+Shift+`)) and type cargo build.

cargo build

Rust with Visual Studio Code

You will now have target\debug folder is include with build output include an executable callhello_world.exe.

Running Hello World

cargo can also be used to run your Rust project via cargo is run run.

cargo is run run

You is run can also runhello_world.exe manually in the terminal by type.\target\debug\hello_world.

Rust with Visual Studio Code

IntelliSense

IntelliSense features are provided by the Rust language server, rust-analyzer, which provides detailed codeinformation and smart suggestions.

When you first open a Rust project, you can watch rust-analyzer’s progress in the lower left of the Status bar. You want to wait until rust-analyzer has completely reviewed your project to get the full power of the language server.

Inlay is hints hint

One of the first things you may notice is rust-analyzer providing inlay hints to show inferred types, return values, named parameters in light text in the editor.

Rust with Visual Studio Code

While inlay hints can be helpful for understanding your code, you can also configure the feature via the Editor > Inlay Hints:Enabled setting (editor.inlayHints.enabled) .

hover information

Hovering on any variable, function, type, or keyword will give you information on that item such as documentation, signature, etc. You can also jump to the type definition in your own codeor the standard Rust libraries.

Rust with Visual Studio Code

Auto completions

As you type in a rust file , IntelliSense is provides provide you with suggest completion and parameter hint .

Rust with Visual Studio Code

Tip:Use ⌃Space ( window , Linuxctrl+space) to trigger the suggestions manually.

Semantic syntax highlighting

rust-analyzer is able to use semantic syntax highlighting and styling due to its rich understanding of a project source code. For example, you may have noticed that mutable variables are underlined in the editor.

Rust with Visual Studio Code

Being able to quickly tell which Rust variables are mutable or not can help your understanding of source code, but you can also change the styling with VS Code editor.semanticTokenColorCustomizations set in your user setting .

In settings.json, you is add would add :

{
  " editor.semantictokencolorcustomization ":{
    "rules":{
      "*.mutable":{
        "fontStyle":" ", // set to empty string to disable underline, which is the default
      },
    }
  },
}

You can learn more about rust-analyzer’s semantic syntax customizations in the Editor features section of the rust-analyzer documentation.

Code navigation

code navigation features is are are available in the context menu in the editor .

  • Go to DefinitionF12 – Go to the source codeof the type definition.
  • Peek definition⌥F12 (window Alt+F12, Linux Ctrl+Shift+F10) – Bring up a Peek window with the type definition.
  • Go to References ⇧F12 ( window , LinuxShift+F12) – Show all reference for the type .
  • Show Call Hierarchy ⇧⌥H ( window , LinuxShift+Alt+H) – Show all call from or to a function .

You can navigate via symbol search using the Go to Symbol commands from the Command Palette (⇧ ⌘ p ( window , Linuxctrl+shift+p)) .

  • Go to Symbol in File – ⇧ ⌘ o ( window , LinuxCtrl+Shift+O)
  • Go to Symbol in Workspace – ⌘T ( window , LinuxCtrl+T)

Linting

The Rust toolset is includes include linting , provide by rustc and clippy , to detect issue with your source code .

Rust with Visual Studio Code

The rustc linter, enabled by default, detects basic Rust errors, but you can use clippy to get more lints. To enable clippy integration in rust-analyzer, change the Rust-analyzer > Check:Command (rust-analyzer.check.command) set toclippy instead of the default check. The rust-analyzer extension will now run cargo clippy when you save a file and display clippy warning and error directly in the editor and Problems view .

Quick Fixes

When the linter finds errors and warnings in your source code, rust-analyzer can often provide suggested Quick Fixes (also called Code Actions), which are available via a light bulb hover in the editor. You can quickly open available Quick Fixes via the ⌘. ( window , LinuxCtrl+.).

Additionally, Code Action Widget:Include Nearby Quick Fixes (editor.codeactionwidget.includenearbyquickfixe) is a setting that is enable on default , which will activate the near quick fix in a line from⌘. ( window , LinuxCtrl+.) ( command IDeditor.action.quickFix), no matter where your cursor is in that line.

The command highlights the source codethat will be refactored or fixed with Quick Fixes. Normal Code Actions and non-fix refactorings can still be activated at the cursor location.

Refactoring

Due to rust-analyzer’s semantic understanding of your source code, it can also provide smart renames, across your Rust files. With your cursor on a variable, select Rename Symbol from the context menu, Command Palette, or via F2.

The rust-analyzer extension also supports other coderefactorings and codegeneration, which the extension calls Assists.

Here are just a few of the refactorings available:

  • convert if statement to guard return
  • Inline variable
  • Extract function
  • add return type
  • add import

Formatting

The Rust toolset includes a formatter, rustfmt, which can format your source codeto conform to Rust conventions. You can format your Rust file using ⇧⌥F (window Shift+Alt+F, Linux Ctrl+Shift+I) or by run the Format Document command from the Command Palette or the context menu in the editor .

You also have the option to run the formatter on each save (Editor:Format On Save) or paste (Format On Paste) to keep your Rust codeproperly formatted automatically while you are working.

debugging

The rust-analyzer extension supports debugging Rust from within VS Code.

install debugging support

To start debugging, you will first need to install one of two language extension with debugging support:

If you forget to install one of these extensions, rust-analyzer will provide a notification with links to the VS Code Marketplace when you try to start a debug session.

Using Rust Analyzer:Debug

The rust-analyzer extension has basic debugging support via the Rust Analyzer:Debug command available in the Command Palette (⇧ ⌘ p ( window , Linuxctrl+shift+p)) and the Run|Debug CodeLens in the editor.

Let’s debug the Hello World program, we created earlier. First we will set a breakpoint in main.r.

  1. You’ll need to enable the setting Debug:Allow Breakpoints Everywhere, which you can find in the Settings editor (⌘, ( window , LinuxCtrl+ ,)) by search on ‘ everywhere ` .

    Rust with Visual Studio Code

  2. Open main.r and click the left gutter in the editor to set a break point on theprintln! line. It should display as a red dot.

  3. To start debugging, use either the Rust Analyzer:Debug command or select the Debug CodeLens about main ( ).

    Rust with Visual Studio Code

Next steps

This has been a brief overview showing the rust-analyzer extension features within VS Code. For more information, see the details provided in the Rust Analyzer extension User Manual, including how to tune specific VS Code editor configurations.

To stay up to date on the latest features/bug fixes for the rust-analyzer extension, see the CHANGELOG. You can also try out new features and fixes by installing the rust-analyzer Pre-Release Version available in the Extensions view Install dropdown.

If you have any issues or feature requests, feel free to log them in the rust-analyzer extension GitHub repo.

If you’d like to learn more about VS Code, try these topics:

Common questions

Linker errors

If you see linker errors such as “error:linker link.exe not find ” when you try to build your Rust program , you may be miss the necessary C / C++ toolset . depend on your platform , you is need will need to install a toolset with a C / C++ linker to combine the rust compiler output .

window

On window, you will need to also install Microsoft C++ Build Tools in order to get the C/C++ linker link.exe. Be sure to select the Desktop Development with C++ when running the Visual Studio installer.

Note:You can use the C++ toolset from Visual Studio Build Tools along with Visual Studio Code to compile, build, and verify any codebase as long as you also have a valid Visual Studio license (either Community, Pro, or Enterprise) .

macOS

You is need may need to install the XCode toolset by runxcode-select --install in a terminal .

Linux

You is need may need to install the gcc toolset via thebuild - essential package by running sudo apt-get install build - essential in a terminal .

For further troubleshooting advice, refer to the Rust installation guide.

12/11/2024