Как запустить rust ubuntu

Обновлено: 25.06.2024

Rust был разработан Mozilla в 2010 году для высококонкурентных и безопасных систем. Синтаксис похож на C и C ++, с блоками кода, очерченными фигурными скобками, пример:

Rust используется в центрах обработки данных такими компаниями, как Dropbox, Postmates, Stac, Wantedly, Doctolib и QIWI, и делает упор на безопасность, контроль расположения памяти и параллелизм. Rust поддерживает такие понятия, как:

  • Абстракции с нулевой стоимостью;
  • Сопоставление с образцом;
  • Минимальное время выполнения;
  • Алгебраические типы данных;
  • Эффективные привязки C.

Rust является open source проектом с открытым исходным кодом и может быть установлен на нескольких платформах. Приведем процесс установки этого очень полезного языка в дистрибутивах Linux на основе Debian / Ubuntu и RHEL.

Требования к установке

  • ОС Linux;
  • Пользователь с привилегиями sudo.

Если вы используете дистрибутив, который не работает с sudo, вам нужно будет использовать команду su для пользователя root вместо использования команды sudo.

Как установить Rust

Первое, что нужно сделать, это установить curl. В дистрибутиве на основе Debian или Ubuntu сделайте это с помощью команды:

В дистрибутивах основанных на Red Hat установите curl с помощью команды:

После установки curl загрузите и установите Rust с помощью команды:

Когда установщик загрузится, он запустится и сначала спросит, хотите ли вы продолжить, настроить или отменить установку(Рис.1)

установка rust

Рис.1

Введите 1, чтобы продолжить. В ходе этого процесса Rust не сможет добавить каталог bin для Cargo (менеджер пакетов и хост для rust) в ваш $ PATH, поэтому вам придется сделать это вручную с помощью команды:

После этого вам нужно будет найти свой пользовательский файл .profile, чтобы использовать измененный $PATH и убедиться, что ваша пользовательская оболочка будет работать в среде Rust. Это достигается с помощью команды:

Наконец, вам нужно установить несколько зависимостей, требуемых командой rust. Для Debian / Ubuntu установите остальные зависимости с помощью команды:

Для CentOS / RHEL используйте команду:

Как проверить установку Rust

Давайте проверим Rust с помощью «Hello, World!» программы. Сначала создайте новый каталог для размещения нашей тестовой программы с помощью команды:

Перейдите в созданную директорию командой:

Создайте новый rust файл командой:

Вставьте следующий пример кода в файл:

Сохраните и закройте файл.

Создайте исполняемый файл Rust с помощью команды:

Будет создан новый исполняемый файл с именем rusttest. Вы можете запустить это новое приложение с помощью команды:

Вы должны увидеть выходные данные приложения, напечатанные как Hello, Rust

Поздравляем, вы установили Rust и использовали его для создания своего первого приложения.

о ржавчине

В следующей статье мы рассмотрим, как установить язык программирования Rust. Мы также увидим, как скомпилировать и запустить базовое приложение на Rust. Это скомпилированный язык программирования общего назначения, который разработан Mozilla. По словам разработчиков, он был разработан так, чтобы «безопасный и практичный язык«. Он поддерживает чисто функциональное, процедурное, императивное и объектно-ориентированное программирование.

Rust - относительно новый язык программирования. Он обещает создавать быстрые и безопасные приложения. Такие компании, как Atlassian, Chef, CoreOS и DropBox, используют Rust. Согласно политике Mozilla, Rust разработан полностью открытым способом и ищет мнения и комментарии сообщества.

Основная цель Rust - быть хороший язык для создания отличных программ на стороне клиента и сервера, которые работают в Интернете. При этом особое внимание уделялось безопасности и контролю распределения памяти. Синтаксис этого языка аналогичен синтаксису C и C ++., с разделенными ключами кодовыми блоками и структурами управления потоком, такими как if, еще, do, в то время как y для.

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

Если кому-то нужна дополнительная информация об этом языке, они могут обратиться к большому количеству существующей документации по нему. Мы можем найти на их сайте из основная книга о ржавчине к официальная документация.

Установите Rust на Ubuntu 18.04

Этот язык программирования можно установить очень просто. Достаточно с использовать завиток. Если он у нас не установлен, мы можем получить его, набрав в терминале (Ctrl + Alt + T):

Как только мы установили curl, мы можем запустить установку. Для этого в том же терминале пишем:

Во время установки мы увидим что-то вроде того, что показано на следующем скриншоте.

Меню при установке Rust

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

Во время предыдущей установки будет установлено несколько пакетов:

  • груз - Менеджер пакетов, используемый Rust.
  • ржавчина - Текущий компилятор Rust.
  • ржавчина - Установщик Rust, который был загружен и запущен.

Хоть они и были установлены правильно, но для корректной работы мне пришлось установить компилятор gcc выше.

Пример приложения с Rust

Пример приложения на Rust

После установки самое время его протестировать. Вот почему мы собираемся написать типичную программу для начала с любого языка программирования. Открываем наш любимый редактор и создаем следующий файл:

Внутри редактора вставляем следующие строки:

Я не буду вдаваться в подробности, что означает каждая строка, но должно быть довольно очевидно, что она напечатает пару строк текста. Если ты заинтересован увидеть больше примеров на Rust, вы можете проконсультироваться Документация с примерами пользователя Rust.

После сохранения файла, в данном случае с именем example.rs, у нас уже есть исходный файл. Теперь мы можем скомпилировать его для создания исполняемого файла:

Приложение Hello World на Rust

Как мы видим на скриншоте, исполняемый файл был создан, имя которого совпадает с именем исходного файла. Это можно запустить, чтобы увидеть наш пример приложения:

Содержание статьи соответствует нашим принципам редакционная этика. Чтобы сообщить об ошибке, нажмите здесь.

Полный путь к статье: Убунлог » Ubuntu » Rust, установите этот язык программирования в Ubuntu 18.04

about Rust

In the next article we are going to take a look at how to install the Rust programming language. We will also see how to compile and run a basic application with Rust. This is a compiled, general-purpose programming language that is being developed by Mozilla. According to its developers, it has been designed to be «a safe and practical language«. It supports pure functional, procedural, imperative, and object-oriented programming.

Rust is a programming language that is relatively new. It promises to create fast and secure applications. Companies like Atlassian, Chef, CoreOS, and DropBox are using Rust. Per Mozilla policy, Rust is developed in a totally open way and seeks input and input from the community.

Rust's main goal is to be a good language for creating great programs, client and server side, that run on the Internet. This placed special emphasis on security and memory distribution control. The syntax of this language is similar to that of C and C ++, with key-delimited code blocks and flow control structures such as if, else, do, while y for.

The language design has been refined through experiences in the development of the Rust compiler itself and the Rust engine. servo navigator. Although it is developed and sponsored by Mozilla and Samsung, claims to be a community project. A large part of the progress comes from community members.

If someone needs more information about this language, they can consult the much documentation that exists about it. We can find on their website from the essential book about Rust to official documentation.

Table of Contents

Install Rust on Ubuntu 18.04

This programming language can be installed in a very simple way. Enough with use curl. In case we don't have it installed, we can get hold of it by typing in a terminal (Ctrl + Alt + T):

Once we have curl installed, we can launch the installation. For this we write in the same terminal:

During the installation we will see something like what can be seen in the following screenshot.

Menu during Rust installation

At this point, it will be necessary to press 1 to continue with the installation. After the installation is finished, we will see the message that we need configure the environment to run the Rust compiler. We are going to solve this by typing in the terminal:

This command will not show us anything, but despite this, we can be sure that our environment is ready to start compiling the Rust programs. We will only have to do this once. The next time you log into the terminal, it will load automatically.

During the previous installation, several packages will be installed:

  • cargo - The package manager used by Rust.
  • rust c - The current Rust compiler.
  • rustup - The Rust installer that was downloaded and run.

Although they were installed correctly, I had to install the gcc compiler higher for correct operation.

Sample application with Rust

Application example made with Rust

After the installation is finished, it is time to test it. So we are going to write the typical program to start with any programming language. We open our favorite editor and create the following file:

Inside the editor we paste the following lines:

I'm not going to go over what each line means, but it should be pretty obvious that it will print a couple of lines of text. If you are interested see more Rust examples, you can consult the Examples documentation by Rust.

Once the file is saved, in this case with the name example.rs, we already have our source file. Now we can compile it to create the executable:

If everything has gone well we will see that the terminal will not show us anything. If there is an error, you will see a message about it.

Hello world application made with Rust

As we can see in the screenshot, an executable file has been created, which has the same name as the source file. This can be run to see our sample application:

The content of the article adheres to our principles of editorial ethics. To report an error click here!.

Full path to article: Ubunlog » Ubuntu » Rust, install this programming language on Ubuntu 18.04


An alternative method to run rust on linux if proton doesn't work


1


1,438 уникальных посетителей
6 добавили в избранное









You can check your Vulkan installation with the command vulkaninfo or vkcube. If there are no errors everything should work

Ubuntu/Debian



To see which Vulkan implementations are currently installed on your system, use the following command:

Start lutris and install the Wine Steam runner.

To show the Manage Runners window click near "Runners", then scroll down and install the Wine Steam runner:

After the installation of the runner select "Configure Runner" and make sure the option "Enable DXVK/VKD3D" is enabled

The steam interface with wine is very glitchy, you can optionally show only the mini version of the library of steam by clicking "Show advanced options" and adding the following text inside the "Arguments" field:

(Thank you TermNCR for the tip!)

Click the Save button and close the window.

Inside the main window of Lutris, click the Wine Steam Tab and select the Add Game option

Insert a Name and select the runner "Wine Steam", then move to the "Game options" tab and insert the Application ID of Rust: 252490
Enable the option "Do not launch game, only open Steam" if you want to show the Steam interface and don't start the game directly (after the installation you can uncheck this for a faster startup of the game)

You can now click the Save button

If you have already downloaded Rust with Proton on Steam for Linux, you can copy the Rust game folder from the proton installation to the lutris/wine installation.

From your home directory, press on the keyboard CTRL+H to show hidden files, then go to the directory

and copy the Rust folder.

Paste the Rust folder inside your steam lutris/wine installation usually located from your home directory to

.local -> share -> lutris -> runners -> winesteam -> prefix64 -> drive_c -> Program Files (x86) -> Steam -> steamapps -> common

(Create steamapps and common folders if they don't exist)

When you will start the installation of Rust, Steam will first check existing files and then download the missing ones.

Select Rust from Lutris and press Play.
Login into steam and search Rust from your library to install the game (if you are using the mini library mode of steam, use the View menu to see the Download progress). After the installation you can start the game from the steam interface.

Inside the game menu don't press the Play button or the game will crash! Linux is not supported anymore, so you can't play on EAC protected servers. There are some linux servers with EAC disabled but you need to use the in-game console to connect.
Press the F1 key and type into the console:

You can also explore servers without EAC using the steam server browser from the View -> Server Menu.

  • Use Borderless window mode, Exclusive mode can give you problems

Читайте также: