Установить rust язык программирования

Install Rust

It looks like you’re running macOS, Linux, or another Unix-like OS. To download Rustup and install Rust, run the following in your terminal, then follow the on-screen instructions. See «Other Installation Methods» if you are on Windows.

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

It looks like you’re running 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».

Windows Subsystem for Linux

If you’re a Windows Subsystem for Linux user run the following in your terminal, then follow the on-screen instructions to install Rust.

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

Rust runs on Windows, Linux, macOS, FreeBSD and NetBSD. If you are on one of these platforms and are seeing this then please report an issue with the following values:

To install Rust, if you are running Unix,
run the following in your terminal, then follow the on-screen instructions.

curl —proto ‘=https’ —tlsv1.2 -sSf https://sh.rustup.rs | sh

If you are running Windows,
download and run rustup‑init.exe then follow the on-screen instructions.

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

If you are running Windows,
download and run rustup‑init.exe then follow the on-screen instructions.

Notes about Rust installation

Getting started

If you’re just getting started with Rust and would like a more detailed walk-through, see our getting started page.

Windows considerations

On Windows, Rust additionally requires the MSVC build tools for Visual Studio 2013 or later. See MSVC prerequistes

For further information about configuring Rust on Windows see the Windows-specific rustup documentation.

Toolchain management with rustup

Rust is installed and managed by the rustup tool. Rust has a 6-week rapid release process and supports a great number of platforms, so there are many builds of Rust available at any time. rustup manages these builds in a consistent way on every platform that Rust supports, enabling installation of Rust from the beta and nightly release channels as well as support for additional cross-compilation targets.

If you’ve installed rustup in the past, you can update your installation by running rustup update .

For more information see the rustup documentation.

Configuring the PATH environment variable

In the Rust development environment, all tools are installed to the ~/.cargo/bin %USERPROFILE%\.cargo\bin directory, and this is where you will find the Rust toolchain, including rustc , cargo , and rustup .

Читайте также:  3 примера системы программирования

Accordingly, it is customary for Rust developers to include this directory in their PATH environment variable. During installation rustup will attempt to configure the PATH . Because of differences between platforms, command shells, and bugs in rustup , the modifications to PATH may not take effect until the console is restarted, or the user is logged out, or it may not succeed at all.

If, after installation, running rustc —version in the console fails, this is the most likely reason.

Uninstall Rust

If at any point you would like to uninstall Rust, you can run rustup self uninstall . We’ll miss you though!

Other installation methods

The installation described above, via rustup , is the preferred way to install Rust for most developers. However, Rust can be installed via other methods as well.

Get help!

Источник

The Rust Programming Language

The first step is to install Rust. We’ll download Rust through rustup , a command line tool for managing Rust versions and associated tools. You’ll need an internet connection for the download.

Note: If you prefer not to use rustup for some reason, please see the Other Rust Installation Methods page for more options.

The following steps install the latest stable version of the Rust compiler. Rust’s stability guarantees ensure that all the examples in the book that compile will continue to compile with newer Rust versions. The output might differ slightly between versions because Rust often improves error messages and warnings. In other words, any newer, stable version of Rust you install using these steps should work as expected with the content of this book.

Command Line Notation

In this chapter and throughout the book, we’ll show some commands used in the terminal. Lines that you should enter in a terminal all start with $ . You don’t need to type the $ character; it’s the command line prompt shown to indicate the start of each command. Lines that don’t start with $ typically show the output of the previous command. Additionally, PowerShell-specific examples will use > rather than $ .

Installing rustup on Linux or macOS

If you’re using Linux or macOS, open a terminal and enter the following command:

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

The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the install is successful, the following line will appear:

Rust is installed now. Great! 

You will also need a linker, which is a program that Rust uses to join its compiled outputs into one file. It is likely you already have one. If you get linker errors, you should install a C compiler, which will typically include a linker. A C compiler is also useful because some common Rust packages depend on C code and will need a C compiler.

On macOS, you can get a C compiler by running:

Linux users should generally install GCC or Clang, according to their distribution’s documentation. For example, if you use Ubuntu, you can install the build-essential package.

Читайте также:  Система программирования программы низкого уровня

Installing rustup on Windows

On Windows, go to https://www.rust-lang.org/tools/install and follow the instructions for installing Rust. At some point in the installation, you’ll receive a message explaining that you’ll also need the MSVC build tools for Visual Studio 2013 or later.

To acquire the build tools, you’ll need to install Visual Studio 2022. When asked which workloads to install, include:

  • “Desktop Development with C++”
  • The Windows 10 or 11 SDK
  • The English language pack component, along with any other language pack of your choosing

The rest of this book uses commands that work in both cmd.exe and PowerShell. If there are specific differences, we’ll explain which to use.

Troubleshooting

To check whether you have Rust installed correctly, open a shell and enter this line:

You should see the version number, commit hash, and commit date for the latest stable version that has been released, in the following format:

rustc x.y.z (abcabcabc yyyy-mm-dd) 

If you see this information, you have installed Rust successfully! If you don’t see this information, check that Rust is in your %PATH% system variable as follows.

If that’s all correct and Rust still isn’t working, there are a number of places you can get help. Find out how to get in touch with other Rustaceans (a silly nickname we call ourselves) on the community page.

Updating and Uninstalling

Once Rust is installed via rustup , updating to a newly released version is easy. From your shell, run the following update script:

To uninstall Rust and rustup , run the following uninstall script from your shell:

Local Documentation

The installation of Rust also includes a local copy of the documentation so that you can read it offline. Run rustup doc to open the local documentation in your browser.

Any time a type or function is provided by the standard library and you’re not sure what it does or how to use it, use the application programming interface (API) documentation to find out!

Источник

Язык программирования Rust

Первым шагом является установка Rust. Мы загрузим Rust, используя инструмент командной строки rustup , предназначенный для управлениями версиями Rust и другими связанными с ним инструментами. Вам понадобится интернет-соединение для его загрузки.

Примечание: если вы по каким-то причинам предпочитаете не использовать rustup, пожалуйста, посетите страницу «Другие методы установки Rust» для получения дополнительных опций.

Следующие шаги устанавливают последнюю стабильную версию компилятора Rust. Благодаря гарантиям стабильности Rust все примеры в книге, которые компилируются, будут компилироваться и в новых версиях Rust. Вывод может немного отличаться в разных версиях, поскольку Rust часто улучшает сообщения об ошибках и предупреждения. Другими словами, любая новая, стабильная версия Rust, которую вы установите с помощью этих шагов, должна работать с содержимым этой книги так, как ожидается.

Условные обозначения командной строки

В этой главе и во всей книге мы будем демонстрировать некоторые команды, используемые в терминале. Строки, которые вы должны вводить в терминале, начинаются с $ . Вам не нужно вводить символ $ ; это подсказка командной строки, отображаемая для обозначения начала каждой команды. Строки, которые не начинаются с $ , обычно показывают вывод предыдущей команды. Кроме того, в примерах, специфичных для PowerShell, будет использоваться > , а не $ .

Читайте также:  Где используется объектно ориентированное программирование

Установка rustup на Linux или macOS

Если вы используете Linux или macOS, пожалуйста, выполните следующую команду:

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

Команда загружает сценарий и запускает установку инструмента rustup , который устанавливает последнюю стабильную версию Rust. Вам может быть предложено ввести пароль. Если установка прошла успешно, появится следующая строка:

Rust is installed now. Great! 

Вам также понадобится компоновщик (linker) — программа, которую Rust использует для объединения своих скомпилированных выходных данных в один файл. Скорее всего, он у вас уже есть. При возникновении ошибок компоновки, вам следует установить компилятор C, который обычно будет включать в себя и компоновщик. Компилятор C также полезен, потому что некоторые распространённые пакеты Rust зависят от кода C и нуждаются в компиляторе C.

На macOS вы можете получить компилятор C, выполнив команду:

Пользователи Linux, как правило, должны устанавливать GCC или Clang в соответствии с документацией их дистрибутива. Например, при использовании Ubuntu можно установить пакет build-essential .

Установка rustup на Windows

На Windows перейдите по адресу https://www.rust-lang.org/tools/install и следуйте инструкциям по установке Rust. На определённом этапе установки вы получите сообщение, предупреждающее, что вам также понадобятся инструменты сборки MSVC для Visual Studio 2013 или более поздней версии.

Чтобы получить инструменты сборки, вам потребуется установить Visual Studio 2022. На вопрос о том, какие компоненты необходимо установить, выберите:

  • “Desktop Development with C++”
  • The Windows 10 or 11 SDK
  • Английский языковой пакет вместе с любым другим языковым пакетом по вашему выбору.

В остальной части этой книги используются команды, которые работают как в cmd.exe, так и в PowerShell. При наличии специфических различий мы объясним, что необходимо сделать в таких случаях.

Устранение возможных ошибок

Чтобы проверить, правильно ли у вас установлен Rust, откройте оболочку и введите эту строку:

Вы должны увидеть номер версии, хэш фиксации и дату фиксации для последней стабильной версии, которая была выпущена, в следующем формате:

rustc x.y.z (abcabcabc yyyy-mm-dd) 

Если вы видите эту информацию, вы успешно установили Rust! Если вы не видите эту информацию, убедитесь, что Rust находится в вашей системной переменной %PATH% следующим образом:

Если все было сделано правильно, но Rust все ещё не работает, есть несколько мест, где вам могут помочь. Узнайте, как связаться с другими Rustaceans (так мы себя называем) на странице сообщества.

Обновление и удаление

После установки Rust с помощью rustup обновление до новой версии не составит труда. В командной оболочке запустите следующий скрипт обновления:

Чтобы удалить Rust и rustup , выполните следующую команду:

Локальная документация

Установка Rust также включает локальную копию документации, чтобы вы могли читать её в автономном режиме. Выполните rustup doc , чтобы открыть локальную документацию в браузере.

Если стандартная библиотека предоставляет тип или функцию, а вы не знаете, что она делает или как её использовать, воспользуйтесь документацией интерфейса прикладного программирования (API), чтобы это узнать!

Источник

Оцените статью