Rust with Visual Studio Code (2023)

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.

Rust with Visual Studio Code (1)

Note: There is also another popular Rust extension in the VS Code Marketplace (extension ID: rust-lang.rust) but this extension is deprecated and rust-analyzer is the recommended 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 Windows, 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 (Windows, Linux Ctrl+Shift+X)) and searching for 'rust-analyzer'. You should install the Release Version.

Rust with Visual Studio Code (2)

We'll discuss many of rust-analyzer features 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 code formatter, 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.

(Video) LIVE 🔴: Getting started with Rust in VS Code

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 pass cargo 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 via code .:

cd hello_worldcode .

Note: Enable Workspace Trust for the new folder as you are the author. You can enable Workspace Trust for your entire project folder parent to avoid being prompted when you create new projects by checking the option to Trust the authors of all the files in parent folder 'my_projects`.

cargo new creates a simple Hello World project with a main.rs source code file and Cargo.toml Cargo manifest file.

src\ main.rs.gitignoreCargo.toml

main.rs has the program's entry function main() and prints "Hello, world!" to the console using println!.

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 (⌃⇧` (Windows, Linux Ctrl+Shift+`)) and type cargo build.

cargo build

Rust with Visual Studio Code (3)

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

Running Hello World

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

cargo run

You can also run hello_world.exe manually in the terminal by typing .\target\debug\hello_world.

Rust with Visual Studio Code (4)

IntelliSense

IntelliSense features are provided by the Rust language server, rust-analyzer, which provides detailed code information 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.

Rust with Visual Studio Code (5)

(Video) Getting Started with Rust on Windows and Visual Studio Code

Inlay hints

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 (6)

While inlay hints can be helpful for understanding your code, you can also disable the feature via the Editor > Inlay Hints: Enabled setting (editor.inlayHints.enabled) or use the Rust Analyzer: Toggle Inlay Hints command to hide or display this extra information.

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 code or the standard Rust libraries.

Rust with Visual Studio Code (7)

Auto completions

As you type in a Rust file, IntelliSense provides you with suggested completions and parameter hints.

Rust with Visual Studio Code (8)

Tip: Use ⌃Space (Windows, Linux Ctrl+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 (9)

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 setting in your user settings.

In settings.json, you would add:

{ "editor.semanticTokenColorCustomizations": { "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 are available in the context menu in the editor.

  • Go to Definition F12 - Go to the source code of the type definition.
  • Peek Definition ⌥F12 (Windows Alt+F12, Linux Ctrl+Shift+F10) - Bring up a Peek window with the type definition.
  • Go to References ⇧F12 (Windows, Linux Shift+F12) - Show all references for the type.
  • Show Call Hierarchy ⇧⌥H (Windows, Linux Shift+Alt+H) - Show all calls from or to a function.

You can navigate via symbol search using the Go to Symbol commands from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

  • Go to Symbol in File - ⇧⌘O (Windows, Linux Ctrl+Shift+O)
  • Go to Symbol in Workspace - ⌘T (Windows, Linux Ctrl+T)

Linting

The Rust toolset includes linting, provided by rustc and clippy, to detect issues with your source code.

(Video) Debugging Rust with Visual Studio Code

Rust with Visual Studio Code (10)

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) setting to clippy instead of the default check. The rust-analyzer extension will now run cargo clippy when you save a file and display clippy warnings and errors 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 ⌘. (Windows, Linux Ctrl+.).

Rust with Visual Studio Code (11)

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 code refactorings and code generation, which the extension calls Assists.

Here are just a few of the refactorings available:

  • Convert if statement to guarded return
  • Inline variable
  • Extract function
  • Add return type
  • Add import

Formatting

The Rust toolset includes a formatter, rustfmt, which can format your source code to conform to Rust conventions. You can format your Rust file using ⇧⌥F (Windows Shift+Alt+F, Linux Ctrl+Shift+I) or by running 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 code properly 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:

  • Microsoft C++ (ms-vscode.cpptools)
  • CodeLLDB (vadimcn.vscode-lldb)

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.

Rust with Visual Studio Code (12)

Using Rust Analyzer: Debug

The rust-analyzer extension has basic debugging support via the Rust Analyzer: Debug command available in the Command Palette (⇧⌘P (Windows, Linux Ctrl+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.rs.

  1. You'll need to enable the setting Debug: Allow Breakpoints Everywhere, which you can find in the Settings editor (⌘, (Windows, Linux Ctrl+,)) by searching on 'everywhere`.

    (Video) IDE Setup For Rust Development

    Rust with Visual Studio Code (13)

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

    Rust with Visual Studio Code (14)

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

    Rust with Visual Studio Code (15)

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:

  • Basic Editing - A quick introduction to the basics of the VS Code editor.
  • Install an Extension - Learn about other extensions are available in the Marketplace.
  • Code Navigation - Move quickly through your source code.

Common questions

Linker errors

If you see linker errors such as "error: linker link.exe not found" when you try to build your Rust program, you may be missing the necessary C/C++ toolset. Depending on your platform, you will need to install a toolset with a C/C++ linker to combine the Rust compiler output.

Windows

On Windows, 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 may need to install the XCode toolset by running xcode-select --install in a terminal.

Linux

(Video) Install Rust and start coding with it on VSCode [ EASIEST METHOD ]

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

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

4/26/2022

FAQs

Can you code Rust in Visual Studio? ›

On Windows, Rust requires certain C++ build tools. You can either download the Microsoft C++ Build Tools, or (recommended) you might prefer just to install Microsoft Visual Studio.

How to setup Rust with VS Code? ›

To install the Rust extension in VS Code follow the following steps: Step 1: Open Visual Studio Code. Step 2: Go to the Extension panel and install the rust-analyzer extension by clicking on the Install button or we can use Ctrl+Shift+X. Step 3: For Debugging support install the CodeLLdb Extension by extension menu.

What is the Rust programming language used for? ›

Rust was built to support system-level programmers who write low-level, byte-tweaking code. It offers access to the raw bits and expects programmers to use it. The language is designed to cohabitate with much of the old C or assembly language code that's part of the lower levels of operating systems and network stacks.

How do I run Rust on Windows? ›

To start using Rust, download the installer, then run the program and follow the onscreen instructions. You may need to install the Visual Studio C++ Build tools when prompted to do so. If you are not on Windows see "Other Installation Methods".

Is Rust easier than C++? ›

C++ may be more forgiving to beginners. Rust features unique concepts not present in other programming languages—like ownership and borrowing. Rust often requires unlearning many patterns from other languages, which could make it easier to learn for the less experienced developer with less 'baggage' to shed.

Is Rust as fast as C++? ›

Rust incorporates a memory ownership model enforced at a compile time. Since this model involves zero runtime overhead, programs written in Rust are not only memory-safe but also fast, leading to performance comparable to C and C++.

Can you code games with Rust? ›

Rust also has a great capacity for game development because of its concurrency. Concurrency in Rust prevents data races and provides epic memory management to help make it impossible for your application to crash. To me, Rust is a well-designed and very clean language.

Is Rust better than go? ›

Must go faster

By contrast, Go is more concerned about simplicity, and it's willing to sacrifice some (run-time) performance for it. But Go's build speed is unbeatable, and that's important for large codebases. Rust is faster than Go. In the benchmarks, Rust was faster, and in some cases, an order of magnitude faster.

Is Rust a replacement for C++? ›

Rust is a new programming language that was designed to be simpler and easier to learn than C++. It doesn't have as many features yet, but it is rapidly gaining popularity. Many developers believe that Rust will eventually replace C++ as the go to programming language.

Should I use Rust or python? ›

Overall, Rust is a much better language than Python and has a better competitive advantage over Python to become one of the dominant programming languages in the world. Therefore, it is one of the best programming languages you should learn.

Is Rust as easy as Python? ›

Which language is easier to learn? Rust is a more demanding language than Python. Its syntax is closer to that of low-level languages. That makes it probably not the best choice as the first technology to learn.

Should I learn C++ or Rust? ›

Here's the big hint – go with Rustlang. Sure, C++ has the lion's share of community support, and huge libraries, but Rust language is so much better in nearly every other way. Rust teaches you to code properly, and the tough love as a beginner is definitely appreciated by those further on in their careers.

What is required to run Rust on PC? ›

OS: Windows 8.1 64bit. Processor: Intel Core i7-3770 / AMD FX-9590 or better. Memory: 10 GB RAM. Graphics: GTX 670 2GB / AMD R9 280 better.

Are windows good in Rust? ›

Final Thoughts

The answer is both yes and no. While steel windows are more resistant to rust than other types of windows, they are not immune. However, you can take steps to protect your steel windows from rust.

Why is Rust so hard to learn? ›

Rust is difficult. It has a complex syntax and a steep learning curve. It is designed to uniquely solve some very challenging problems in programming. However, as a beginner, using Cuda or MPI on Rust is not very simple compared to the other options like Swift and Go.

Is Rust an OOP language? ›

Rust is influenced by many different programming paradigms including OOP; we explored, for example, the features that came from functional programming in Chapter 13. Arguably, object-oriented programming languages do tend to share certain common characteristics, namely objects, encapsulation, and inheritance.

How long will it take to learn Rust? ›

Let us not beat around the bush: Rust is not easy to learn. I think it took me nearly 1 year of full-time programming in Rust to become proficient and no longer have to read the documentation every 5 lines of code.

How much do Rust developers make? ›

How much do Rust developers make? The salaries of candidates in this role range from a low of $130,000 to a high of $230,000, with a median salary of $165,000.

Why Rust is most loved programming language? ›

In programming, Rust is one of the most loved languages. It is a programming language focused on memory safety, protection, high performance during the processing of large amounts of data, concurrency and a highly efficient compiler.

How close is Rust to C? ›

On per-function basis Rust code is about the same size as C, but there's a problem of "generics bloat". Generic functions get optimized versions for each type they're used with, so it's possible to end up with 8 versions of the same function.

Is Rust good for high level programming? ›

Rust is a low-level programming language with direct access to hardware and memory, which makes it a great solution for embedded and bare-metal development. You can use Rust to write operation systems or microcontroller applications.

Is Rust the safest programming language? ›

Well, unlike C, Rust is a safe programming language. But, like C, Rust is an unsafe programming language. More accurately, Rust contains both a safe and unsafe programming language. Rust can be thought of as a combination of two programming languages: Safe Rust and Unsafe Rust.

Is programming in Rust fun? ›

Of the respondents using Rust at work, 89% said their teams found it enjoyable and fun to program. The top reason given by respondents for why they use Rust at work was that Rust allowed them “to build relatively correct and bug-free software.” Only 3% of those surveyed said Rust was a risky choice for production use.

Is Rust worth it 2022 programming? ›

RUST is an excellent language to learn in 2022. It is fast, safe, concurrent, and portable. It also has great tooling and a thriving community. If you are looking for a systems programming language, RUST is the perfect choice.

Should I learn Swift or Rust? ›

There's hardly any support for building iOS, macOS, and other Apple OS apps with Rust, and most developers use Swift for the sole purpose of building mobile applications, unlike Rust, where the developers are actively exploring use cases for the language with systems programming being the top of the list.

Should I learn Rust or elixir? ›

Rust offers concurrency as well, but Elixir performs better in distributed architectures. Security: Guaranteed memory safety is the primary reason developers choose Rust. Because variables and memory are tightly controlled, Rust offers better security than Elixir applications.

Why Rust language is not popular? ›

Asked why developers have stopped using Rust, the most common response is that the respondent's company doesn't use it, suggesting an adoption issue. Other common reasons are the learning curve, a lack of necessary libraries, and a lack of integrated development environment (IDE) support.

Is Rust the future of programming? ›

With both developers and major technology brands recognizing Rust's potential, it's set to be one of the most used and popular programming languages in 2023 (and beyond).

Will Rust overtake Python? ›

Performance is a major reason why Rust is overtaken Python. There is no virtual machine or interpreter between your code and the computer since Rust is compiled directly into machine code. Another significant advantage of Rust over Python is its thread and memory management.

Is Rust going to replace Python? ›

Rust may not replace Python outright, but it has consumed more and more of JavaScript tooling and there are increasingly many projects trying to do the same with Python/Data Engineering.

Which language will replace Python? ›

Julia is becoming more popular lately.

Python has been a popular programming language for many years, but there is speculation that Julia may gradually replace it. Julia is a newer language that has been gaining popularity due to its speed and flexibility.

Is Rust good for low level programming? ›

Rust is aimed at being a modern-day systems programming language. It is low level enough to provide a lot of control, it compiles down to the smallest binary possible and runs very fast with little overhead.

What language could replace C++? ›

Some programmers consider popular languages like Rust, Go, D, and Carbon as C/C++ replacements.

Why is Rust faster than Python? ›

Rust is faster and can be more than twice as fast as Python. Since Rust is compiled directly into machine code, there is no interpreter or virtual machine between the code and the hardware. Another factor that improves the performance of Rust is its memory management.

What IDE can I use for Rust? ›

Visual Studio Code remains the IDE most commonly used for Rust development (40%), followed by CLion (24%) and IntelliJ IDEA (19%).

Can you code games in Visual Studio? ›

Visual Studio offers a great set of tools for developing DirectX games, from writing shader code and designing assets, to debugging and profiling graphics—all in the same familiar Visual Studio IDE.

Can I use Rust in C++? ›

Accessing Rust code and data from C++

A common option for accessing Rust code and data from C++ is to use cbindgen, which generates C++ header files. for Rust crates that expose a public C API. cbindgen is a very powerful tool, and this section only covers some basic uses of it.

Videos

1. Rust Programming - VSCode Extension!
(Code of the Future)
2. Beginners Guide to Rust code compilation and debugging in VSCode IDE
(Prodramp)
3. My VSCode setup: Rust-analyzer for local+remote work
(JaJakub)
4. RUST Hello World In Visual Studio Code
(Asim Code)
5. Rust 101 - How to set up VS Code for Rust
(Rust Ing)
6. Rust in 100 Seconds
(Fireship)
Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated: 02/23/2023

Views: 5566

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.