Rust

Программные средства разработки

Модераторы: Olej, vikos

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Rust

Непрочитанное сообщение Olej » 13 фев 2018, 18:03

Rust — мультипарадигмальный компилируемый язык программирования общего назначения, спонсируемый Mozilla Research, сочетающий парадигмы функциональногои процедурного программирования с объектной системой, основанной на типажах, и с управлением памятью через понятие «владения» (систему аффинных типов, позволяющую обходиться без сборки мусора). После нескольких лет активной разработки (с 2006 года) первая стабильная версия вышла только 15 мая 2015 года, после чего новые версии выходят раз в 6 недель. Язык компилируемый и позиционируется как альтернатива С/С++, что уже само по себе интересно, так как даже претендентов на такую конкуренцию не так уж и много.

Rust разрабатывается одновременно для разнообразных платформ: Windows, Linux, Darwin/MacOS, FreeBSD, NetBSD и др. Поэтому для установки Rust (последней актуальной версии) в вашей системе предлагается (платформа определится автоматически) скопировать и запустить соответствующий скрипт. Для Linux это будет скрипт:

Код: Выделить всё

[olej@dell own.BOOKs]$ curl https://sh.rustup.rs -sSf | sh
info: downloading installer

Welcome to Rust!

This will download and install the official compiler for the Rust programming 
language, and its package manager, Cargo.

It will add the cargo, rustc, rustup and other commands to Cargo's bin 
directory, located at:

  /home/olej/.cargo/bin

This path will then be added to your PATH environment variable by modifying the
profile files located at:

  /home/olej/.profile
  /home/olej/.bash_profile

You can uninstall at any time with rustup self uninstall and these changes will
be reverted.

Current installation options:

   default host triple: x86_64-unknown-linux-gnu
     default toolchain: stable
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation


info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2018-01-04, rust version 1.23.0 (766bd11c8 2018-01-01)
info: downloading component 'rustc'
 45.0 MiB /  45.0 MiB (100 %)   3.1 MiB/s ETA:   0 s                
info: downloading component 'rust-std'
 61.2 MiB /  61.2 MiB (100 %)   3.2 MiB/s ETA:   0 s                
info: downloading component 'cargo'
  4.0 MiB /   4.0 MiB (100 %)   3.1 MiB/s ETA:   0 s                
info: downloading component 'rust-docs'
  4.5 MiB /   4.5 MiB (100 %)   3.3 MiB/s ETA:   0 s                
info: installing component 'rustc'
info: installing component 'rust-std'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: default toolchain set to 'stable'

  stable installed - rustc 1.23.0 (766bd11c8 2018-01-01)


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
Как легко видеть, это бинарная установка, производится в домашний каталог HOME/.cargo, не требует прав root (т. е. не создаёт дополнительной опасности), может быть так же чисто деинсталлирована (командой rustup self uninstall) и вам остаётся только установить переменную $PATH:
export PATH=$HOME/.cargo/bin:$PATH
Если же вас смущает бинарная инсталляция под Linux, или хотите другую или девелоперскую версию, или исходный код системы, то вы можете всё это найти в архиве дистрибутивов Rust (для всех платформ):

Код: Выделить всё

[olej@dell lang_install]$ ls -l rust*
-rw-rw-r-- 1 olej olej 187313088 фев 13 15:45 rust-1.23.0-x86_64-unknown-linux-gnu.tar.gz
-rw-rw-r-- 1 olej olej  24537507 фев 13 15:47 rustc-1.4.0-src.tar.gz
-rw-rw-r-- 1 olej olej   7720195 фев 13 15:49 rust-docs-1.12.1-x86_64-unknown-linux-gnu.tar.gz

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 13 фев 2018, 19:07

Ресурсы по Rust:

Rust — невероятно быстрый язык для системного программирования (сайт проекта)

The Rust Programming Language (описание языка)

Архив дистрибутивов Rust

Rust на примерах

Перевод «The Rust Programming Language»

The Rust Standard Library

Учитывая, что 1-я стабильная версия Rust была представлена только весной 2015 года - меньше 3-х лет назад, на удивление много информационных материалов по Rust представлено на русском языке (для быстрого въезжания в предмет).

P.S. Во сколько энтузиастов!

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 13 фев 2018, 19:24

Olej писал(а): Поэтому для установки Rust (последней актуальной версии) в вашей системе предлагается (платформа определится автоматически) скопировать и запустить соответствующий скрипт. Для Linux это будет скрипт:

Код: Выделить всё

[olej@dell ~]$ which rustc
~/.cargo/bin/rustc
Файл hello.rs

Код: Выделить всё

// Эта строка является комментарием и она будет проигнорирована компилятором
// Протестировать код можно нажав на кнопку "Run" вот тут ->
// так же можно использовать клавиатуру, нажав сочетание клавиш "Ctrl + Enter"

// Это главная функция. С неё начинается исполнение любой программы
fn main() {
    // Следующий код будет исполнен в момент, когда будет запущен исполняемый файл
    // Отображаем текст в консоли
    println!("Привет, мир!");
}
Компиляция:

Код: Выделить всё

[olej@dell rust]$ rustc hello.rs
И в итоге:

Код: Выделить всё

[olej@dell rust]$ ./hello 
Привет, мир!

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 12:36

Olej писал(а):

Код: Выделить всё

[olej@dell ~]$ which rustc
~/.cargo/bin/rustc
Компиляция:

Код: Выделить всё

[olej@dell rust]$ rustc hello.rs
Относительно технологии...
Это показана ручная компиляция, однако руководства (сайт) предлагают другую технологию, построение проекта и использование менеджера проектов - команды cargo:

Код: Выделить всё

[olej@dell rust]$ which cargo
~/.cargo/bin/cargo

[olej@dell rust]$ cargo --help
Rust's package manager

Usage:
    cargo <command> [<args>...]
    cargo [options]

Options:
    -h, --help          Display this message
    -V, --version       Print version info and exit
    --list              List installed commands
    --explain CODE      Run `rustc --explain CODE`
    -v, --verbose ...   Use verbose output (-vv very verbose/build.rs output)
    -q, --quiet         No output printed to stdout
    --color WHEN        Coloring: auto, always, never
    --frozen            Require Cargo.lock and cache are up to date
    --locked            Require Cargo.lock is up to date
    -Z FLAG ...         Unstable (nightly-only) flags to Cargo

Some common cargo commands are (see all commands with --list):
    build       Compile the current project
    check       Analyze the current project and report errors, but don't build object files
    clean       Remove the target directory
    doc         Build this project's and its dependencies' documentation
    new         Create a new cargo project
    init        Create a new cargo project in an existing directory
    run         Build and execute src/main.rs
    test        Run the tests
    bench       Run the benchmarks
    update      Update dependencies listed in Cargo.lock
    search      Search registry for crates
    publish     Package and upload this project to the registry
    install     Install a Rust binary
    uninstall   Uninstall a Rust binary

See 'cargo help <command>' for more information on a specific command.
Новый пустой проект может создаваться так:

Код: Выделить всё

[olej@dell rust]$ cargo new xxx --bin
     Created binary (application) `xxx` project

[olej@dell rust]$ tree xxx
xxx
├── Cargo.toml
└── src
    └── main.rs
    
1 directory, 2 files

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 12:45

Olej писал(а): Новый пустой проект может создаваться так:

Код: Выделить всё

[olej@dell rust]$ cargo new xxx --bin
     Created binary (application) `xxx` project

[olej@dell rust]$ tree xxx
xxx
├── Cargo.toml
└── src
    └── main.rs
    
1 directory, 2 files
Вот что в шаблоне такого проекта:

Код: Выделить всё

[olej@dell xxx]$ pwd
/home/olej/2018_WORK/own.BOOKs/ManyLang/rust/xxx

[olej@dell xxx]$ cat Cargo.toml 
[package]
name = "xxx"
version = "0.1.0"
authors = ["Olej <o.tsiliuric@yandex.ua>"]
[dependencies]

[olej@dell xxx]$ cat src/main.rs
fn main() {
    println!("Hello, world!");
}
А дальше вы начинаете туда вписывать что надо...

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 12:47

Olej писал(а):А дальше вы начинаете туда вписывать что надо...
И далее ...

Код: Выделить всё

[olej@dell xxx]$ pwd
/home/olej/2018_WORK/own.BOOKs/ManyLang/rust/xxx

[olej@dell xxx]$ cargo build
   Compiling xxx v0.1.0 (file:///home/olej/2018_WORK/own.BOOKs/ManyLang/rust/xxx)
    Finished dev [unoptimized + debuginfo] target(s) in 0.96 secs
[olej@dell xxx]$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    └── debug
        ├── build
        ├── deps
        │   └── xxx-519fdaccd45b1cc9
        ├── examples
        ├── incremental
        ├── native
        ├── xxx
        └── xxx.d

8 directories, 6 files

[olej@dell xxx]$ target/debug/xxx
Hello, world!

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 12:52

Olej писал(а):И далее ...
Все опции сборки проекта:

Код: Выделить всё

[olej@dell xxx]$ cargo build -h
Compile a local package and all of its dependencies

Usage:
    cargo build [options]

Options:
    -h, --help                   Print this message
    -p SPEC, --package SPEC ...  Package to build
    --all                        Build all packages in the workspace
    --exclude SPEC ...           Exclude packages from the build
    -j N, --jobs N               Number of parallel jobs, defaults to # of CPUs
    --lib                        Build only this package's library
    --bin NAME                   Build only the specified binary
    --bins                       Build all binaries
    --example NAME               Build only the specified example
    --examples                   Build all examples
    --test NAME                  Build only the specified test target
    --tests                      Build all tests
    --bench NAME                 Build only the specified bench target
    --benches                    Build all benches
    --all-targets                Build all targets (lib and bin targets by default)
    --release                    Build artifacts in release mode, with optimizations
    --features FEATURES          Space-separated list of features to also build
    --all-features               Build all available features
    --no-default-features        Do not build the `default` feature
    --target TRIPLE              Build for the target triple
    --manifest-path PATH         Path to the manifest to compile
    -v, --verbose ...            Use verbose output (-vv very verbose/build.rs output)
    -q, --quiet                  No output printed to stdout
    --color WHEN                 Coloring: auto, always, never
    --message-format FMT         Error format: human, json [default: human]
    --frozen                     Require Cargo.lock and cache are up to date
    --locked                     Require Cargo.lock is up to date
    -Z FLAG ...                  Unstable (nightly-only) flags to Cargo

If the --package argument is given, then SPEC is a package id specification
which indicates which package should be built. If it is not given, then the
current package is built. For more information on SPEC and its format, see the
`cargo help pkgid` command.

All packages in the workspace are built if the `--all` flag is supplied. The
`--all` flag is automatically assumed for a virtual manifest.
Note that `--exclude` has to be specified in conjunction with the `--all` flag.

Compilation can be configured via the use of profiles which are configured in
the manifest. The default profile for this command is `dev`, but passing
the --release flag will use the `release` profile instead.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 12:57

Olej писал(а): Все опции сборки проекта:
В частности (что очень важно!):

Код: Выделить всё

[olej@dell xxx]$ cargo build --release
   Compiling xxx v0.1.0 (file:///home/olej/2018_WORK/own.BOOKs/ManyLang/rust/xxx)
    Finished release [optimized] target(s) in 0.65 secs

[olej@dell xxx]$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── debug
    │   ├── build
    │   ├── deps
    │   │   └── xxx-519fdaccd45b1cc9
    │   ├── examples
    │   ├── incremental
    │   ├── native
    │   ├── xxx
    │   └── xxx.d
    └── release
        ├── build
        ├── deps
        │   └── xxx-460f80de27813036
        ├── examples
        ├── incremental
        ├── native
        ├── xxx
        └── xxx.d

14 directories, 9 files

[olej@dell xxx]$ target/release/xxx
Hello, world!

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 13:40

Olej писал(а):Файл hello.rs
Проверяю, в каком виде связывания (статическое, динамическое) создаёт приложение Rust:

Код: Выделить всё

[olej@dell rust]$ ls -l hello
-rwxrwxr-x 1 olej olej 4306848 фев 13 18:17 hello

[olej@dell rust]$ ldd hello
    linux-vdso.so.1 (0x00007fff8e9bc000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00007f4df988d000)
    librt.so.1 => /lib64/librt.so.1 (0x00007f4df9685000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f4df9467000)
    libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f4df9250000)
    libc.so.6 => /lib64/libc.so.6 (0x00007f4df8e8a000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f4df9d01000)

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Rust

Непрочитанное сообщение Olej » 14 фев 2018, 16:29

Хорошее описание конкретного примера ... но оно понятно и пошагово расписывает технологию Rust-приложений: Rust: скачиваем ленту и парсим JSON
22 Января 2018
В частности:
Во-первых, мы должны добавить пакет clap в качестве зависимости.
Для этого мы должны указать название и версию в Cargo.toml:

Код: Выделить всё

[dependencies]
clap = "2.29"
Если вы сейчас запустите cargo build, то clap будет скомпилирован вместе с нашей программой. Для того чтобы использовать CLAP, мы должны указать Rust, что используем библиотеку (crate в терминологии Rust). Мы также должны внести используемые нами типы в пространство имён. CLAP имеет очень удобный API, который даёт нам возможность настолько глубокой настройки, насколько нам это нужно.

Код: Выделить всё

extern crate clap;
use clap::App;
Дальше, подробнее, про связывание с библиотеками см. в обсуждениях конкретного кода: код на Rus

Ответить

Вернуться в «Инструменты программирования»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 1 гость