Rust: новый подход к снаряду...

Вопросы написания собственного программного кода (на любых языках)

Модератор: Olej

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

Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 19:43

Самое время вернуться к теме Rust : Rust | код на Rust

И рассматривать это в разделе Программирование
И тем более, что в самые ближайшие дни в издательстве BHV выходит книга (инсайдерская информация :-D ):
2861_978-5-9775-1166-7.jpg
2861_978-5-9775-1166-7.jpg (51.76 КБ) 666 просмотров
Rust в действии
Макнамара Тим
Артикул 2861
ISBN 978-5-9775-1166-7
Количество страниц 528
Формат издания 197 x 250 мм
Печать Черно-белая
До конца 2018 года на главной странице Rust посетителей встречало сообщение:
«Rust — язык системного программирования, работающий поразительно быстро,
не допускающий ошибок сегментации и гарантирующий безопасность потоков».
Здесь полный архив кодов к книге:
Welcome to Rust in Action source code
Полный разархивированный архив:

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

olej@R420:~/2022/Rust$ du -hs code-1st-edition 
6,2M	code-1st-edition

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

Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 20:24

Продолжение темы Rust
И освежение ссылок, которые менялись...

https://www.rust-lang.org/ru/ - сайт проекта Rust, и даже в реинкарнации русского языка.

Rust на примерах

The Rust Programming Language (оригинал)
Язык программирования Rust (перевод)
От Стива Клабника и Кэрол Николс, при поддержке других участников сообщества Rust
В этой версии учебника предполагается, что вы используете Rust 1.62 (выпущена 30.06.2022) или новее.

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

Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 20:42

Установка
Мы загрузим Rust, используя инструмент командной строки rustup, предназначенный для управлениями версиями Rust и другими связанными с ним инструментами.
Если вы используете Linux или macOS, пожалуйста, выполните следующую команду:

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

$ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh
Команда скачивает скрипт и начинает установку инструмента rustup, одновременно с установкой последней стабильной версии Rust. Вас могут запросить ввести локальный пароль. При успешной установке вы увидите следующий вывод:

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

Rust is installed now. Great!

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

Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 20:59

Olej писал(а):
27 окт 2022, 20:42
Установка
Но у меня Rust уже установлен, 4 года назад, и его следует просто обновить:

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

olej@R420:~/.cargo/bin$ pwd
/home/olej/.cargo/bin

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

olej@R420:~$ rustup update stable
info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2022-09-22, rust version 1.64.0 (a55dd71d5 2022-09-19)
info: downloading component 'rust-std' for 'armv7-unknown-linux-gnueabihf'
 24.9 MiB /  24.9 MiB (100 %)   2.9 MiB/s in  8s ETA:  0s
info: downloading component 'cargo'
  6.4 MiB /   6.4 MiB (100 %)   2.8 MiB/s in  2s ETA:  0s
info: downloading component 'clippy'
  2.8 MiB /   2.8 MiB (100 %)   2.7 MiB/s in  1s ETA:  0s
info: downloading component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %)   2.9 MiB/s in  6s ETA:  0s
info: downloading component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   2.9 MiB/s in  9s ETA:  0s
info: downloading component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)   2.5 MiB/s in 20s ETA:  0s
info: downloading component 'rustfmt'
  4.3 MiB /   4.3 MiB (100 %)   2.6 MiB/s in  1s ETA:  0s
info: removing previous version of component 'rust-std' for 'armv7-unknown-linux-gnueabihf'
info: removing previous version of component 'cargo'
info: removing previous version of component 'clippy'
info: removing previous version of component 'rust-docs'
info: removing previous version of component 'rust-std'
info: removing previous version of component 'rustc'
info: removing previous version of component 'rustfmt'
info: installing component 'rust-std' for 'armv7-unknown-linux-gnueabihf'
 24.9 MiB /  24.9 MiB (100 %)   9.1 MiB/s in  2s ETA:  0s
info: installing component 'cargo'
info: installing component 'clippy'
info: installing component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %)   6.3 MiB/s in  2s ETA:  0s
info: installing component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   9.1 MiB/s in  3s ETA:  0s
info: installing component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)  10.2 MiB/s in  5s ETA:  0s
info: installing component 'rustfmt'

  stable-x86_64-unknown-linux-gnu updated - rustc 1.64.0 (a55dd71d5 2022-09-19) (from rustc 1.60.0 (7737e0b5c 2022-04-04))

info: checking for self-updates
info: downloading self-update

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

olej@R420:~/.cargo/bin$ which rustc
/home/olej/.cargo/bin/rustc

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

Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 23:10

Olej писал(а):
27 окт 2022, 20:59
у меня Rust уже установлен, 4 года назад, и его следует просто обновить:
Только у меня тулчайн был тогда настроен по дефаулту на ARM процессор ... и я это временно уберу:

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

olej@R420:~/.cargo/bin$ rustup toolchain list
stable-armv7-unknown-linux-gnueabihf (default)
stable-x86_64-unknown-linux-gnu

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

olej@R420:~/.cargo/bin$ rustup toolchain uninstall stable-armv7-unknown-linux-gnueabihf
info: uninstalling toolchain 'stable-armv7-unknown-linux-gnueabihf'
info: toolchain 'stable-armv7-unknown-linux-gnueabihf' uninstalled

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

olej@R420:~/.cargo/bin$ rustup toolchain list
stable-x86_64-unknown-linux-gnu

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

Re: Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 23:24

Olej писал(а):
27 окт 2022, 20:42
Установка
Другой способ установки ... тоже достаточно свежей версии, но более надёжный - из стандартного репозитория:

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

olej@R420:~/.cargo/bin$ aptitude search rust | grep '  rust'
p  rust-all - Rust systems programming language - all developer tools
p  rust-clippy - Rust linter
p  rust-clippy:i386 - Rust linter
v  rust-clippy:any - 
p  rust-doc - Rust systems programming language - Documentation
p  rust-gdb - Rust debugger (gdb)
p  rust-lldb - Rust debugger (lldb)
p  rust-src - Rust systems programming language - source code
p  rustc - Rust systems programming language
p  rustc:i386 - Rust systems programming language
v  rustc:any - 
p  rustdoc-stripper - Strip rustdoc comments from source code
v  rustdoc-stripper:any - 
p  rustfmt - Rust formatting helper
p  rustfmt:i386 - Rust formatting helper
v  rustfmt:any - 
p  rusty-tags - generate tags for source code navigation for a cargo project
v  rusty-tags:any - 

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

olej@R420:~/.cargo/bin$ aptitude show rust-all
Пакет: rust-all                                  
Версия: 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1
Новый: да
Состояние: не установлен
Приоритет: необязательный
Раздел: universe/devel
Сопровождающий: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Архитектура: all
Размер в распакованном виде: 259 k
Зависит: llvm-14, rustc (>= 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1), rustfmt (>= 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1), rust-clippy (>=
         1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1), rust-gdb (>= 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1) | rust-lldb (>=
         1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1), cargo
Рекомендует: cargo (>= 0.62.0~~), cargo (< 0.63.0~~)
Предлагает: rust-doc (>= 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1), rust-src (>= 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1),
            libstd-rust-dev-wasm32 (>= 1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1), libstd-rust-dev-windows (>=
            1.61.0+dfsg1~llvm-1~exp1ubuntu0.20.04.1)
Описание: Rust systems programming language - all developer tools
 Rust is a curly-brace, block-structured expression language.  It visually resembles the C language family, but differs significantly in
 syntactic and semantic details.  Its design is oriented toward concerns of "programming in the large", that is, of creating and maintaining
 boundaries - both abstract and operational - that preserve large-system integrity, availability and concurrency. 
 
 It supports a mixture of imperative procedural, concurrent actor, object-oriented and pure functional styles.  Rust also supports generic
 programming and meta-programming, in both static and dynamic styles. 
 
 This package is an empty metapackage that depends on all developer tools in the standard rustc distribution that have been packaged for
 Debian.
Домашняя страница: http://www.rust-lang.org/

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

Re: Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 23:54

Olej писал(а):
27 окт 2022, 23:24
Другой способ установки ... тоже достаточно свежей версии, но более надёжный - из стандартного репозитория:
Только сначала - деинсталляция ручной установки:

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

olej@R420:~/.cargo/bin$ rustup self uninstall

Thanks for hacking in Rust!

This will uninstall all Rust toolchains and data, and remove
$HOME/.cargo/bin from your PATH environment variable.

Continue? (y/N) y

info: removing rustup home
info: removing cargo home
info: removing rustup binaries
info: rustup is uninstalled
Но в моём репозитории что-то напутано с версиями:

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

olej@R420:~$ sudo apt install rust-all
Чтение списков пакетов… Готово
Построение дерева зависимостей       
Чтение информации о состоянии… Готово
Некоторые пакеты не могут быть установлены. Возможно, то, что вы просите,
неосуществимо, или же вы используете нестабильную версию дистрибутива, где
запрошенные вами пакеты ещё не созданы или были удалены из Incoming.
Следующая информация, возможно, вам поможет:

Следующие пакеты имеют неудовлетворённые зависимости:
 rust-all : Зависит: llvm-14 но он не может быть установлен
E: Невозможно исправить ошибки: у вас зафиксированы сломанные пакеты.
LLVM v.14 - нет, максимум LLVM v.12:

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

olej@R420:~$ aptitude search llvm-14

olej@R420:~$ aptitude search llvm-12
p   libllvm-12-ocaml-dev                                           - Modular compiler and toolchain technologies, OCaml bindings              
v   libllvm-12-ocaml-dev-ely59                                     -                                                                          
p   llvm-12                                                        - Modular compiler and toolchain technologies                              
p   llvm-12:i386                                                   - Modular compiler and toolchain technologies                              
p   llvm-12-dev                                                    - Modular compiler and toolchain technologies, libraries and headers       
p   llvm-12-dev:i386                                               - Modular compiler and toolchain technologies, libraries and headers       
p   llvm-12-doc                                                    - Modular compiler and toolchain technologies, documentation               
p   llvm-12-examples                                               - Modular compiler and toolchain technologies, examples                    
p   llvm-12-linker-tools                                           - Modular compiler and toolchain technologies - Plugins                    
p   llvm-12-linker-tools:i386                                      - Modular compiler and toolchain technologies - Plugins                    
p   llvm-12-runtime                                                - Modular compiler and toolchain technologies, IR interpreter              
p   llvm-12-runtime:i386                                           - Modular compiler and toolchain technologies, IR interpreter              
p   llvm-12-tools                                                  - Modular compiler and toolchain technologies, tools                       
p   llvm-12-tools:i386                                             - Modular compiler and toolchain technologies, tools                       

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

Re: Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 27 окт 2022, 23:59

Olej писал(а):
27 окт 2022, 23:54
Но в моём репозитории что-то напутано с версиями:
Поэтому повторю рекомендуюмую инсталляцию:

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

olej@R420:~$ curl --proto '=https' --tlsv1.3 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.

Rustup metadata and toolchains will be installed into the Rustup
home directory, located at:

  /home/olej/.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory is located at:

  /home/olej/.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added 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/.bashrc

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 (default)
               profile: default
  modify PATH variable: yes

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

info: profile set to 'default'
info: default host triple is x86_64-unknown-linux-gnu
info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2022-09-22, rust version 1.64.0 (a55dd71d5 2022-09-19)
info: downloading component 'cargo'
  6.4 MiB /   6.4 MiB (100 %)   2.9 MiB/s in  2s ETA:  0s
info: downloading component 'clippy'
info: downloading component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %)   3.2 MiB/s in  6s ETA:  0s
info: downloading component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   3.0 MiB/s in  9s ETA:  0s
info: downloading component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)   3.1 MiB/s in 17s ETA:  0s
info: downloading component 'rustfmt'
  4.3 MiB /   4.3 MiB (100 %)   3.1 MiB/s in  1s ETA:  0s
info: installing component 'cargo'
info: installing component 'clippy'
info: installing component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %)   5.4 MiB/s in  2s ETA:  0s
info: installing component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   9.9 MiB/s in  2s ETA:  0s
info: installing component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)  12.2 MiB/s in  4s ETA:  0s
info: installing component 'rustfmt'
info: default toolchain set to 'stable-x86_64-unknown-linux-gnu'

  stable-x86_64-unknown-linux-gnu installed - rustc 1.64.0 (a55dd71d5 2022-09-19)


Rust is installed now. Great!

To get started you may need to restart your current shell.
This would reload your PATH environment variable to include
Cargo's bin directory ($HOME/.cargo/bin).

To configure your current shell, run:
source "$HOME/.cargo/env"

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

olej@R420:~$ source "$HOME/.cargo/env"

olej@R420:~$ which rustc
/home/olej/.cargo/bin/rustc

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

olej@R420:~$ rustc --version
rustc 1.64.0 (a55dd71d5 2022-09-19)

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

olej@R420:~$ du -hs .cargo .rustup 
16M	.cargo
1,1G	.rustup

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

olej@R420:~$ cargo search num
    Updating crates.io index
num = "0.4.0"                       # A collection of numeric types and traits for Rust, including bigint, complex, rational, ran…
helper_fn = "0.1.0"                 # A macro to create closure-like helper functions.
z3d = "0.1.0"                       # Z3 DSL interface for Rust
treebender = "0.1.1"                # An HDPSG inspired symbolic NLP library for Rust
num-primes = "0.3.0"                # A Rust Library For Generating Large Prime and Composite Numbers using num with a simplistic…
spartan = "0.7.1"                   # High-speed zkSNARKs without trusted setup
resource_proof = "1.0.39"           # A 'proof' of bandwidth, cpu and storage for nodes in a decentralised network.
concurrent_prime_sieve = "0.3.3"    # Tools for generating filters and collections with primes concurrently. Rust implementation …
num_enum_derive = "0.5.7"           # Internal implementation details for ::num_enum (Procedural macros to make inter-operation b…
num_enum = "0.5.7"                  # Procedural macros to make inter-operation between primitives and enums easier.
... and 1650 crates more (use --limit N to see more)

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

Re: Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 28 окт 2022, 16:47

Olej писал(а):
27 окт 2022, 19:43
в издательстве BHV выходит книга
Olej писал(а):
27 окт 2022, 19:43
Здесь полный архив кодов к книге:
Пойду по этой книге ... точнее по примерам из архивов кодов к книге.

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

olej@R420:~$ which cargo
/home/olej/.cargo/bin/cargo
Создаю проект (на любом пути):

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

olej@R420:~$ cargo new hello
     Created binary (application) `hello` package

olej@R420:~$ tree hello
hello
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files
Вот он создал (подтянул):

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

olej@R420:~$ cat hello/src/main.rs 
fn main() {
    println!("Hello, world!");
}
Компиляция + выполнение:

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

olej@R420:~$ cd hello/

olej@R420:~/hello$ cargo run

   Compiling hello v0.1.0 (/home/olej/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 0.74s
     Running `target/debug/hello`
Hello, world!
Вот что произошло (поменялось):

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

olej@R420:~/hello$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    └── debug
        ├── build
        ├── deps
        │   ├── hello-f10f454b064da970
        │   └── hello-f10f454b064da970.d
        ├── examples
        ├── hello
        ├── hello.d
        └── incremental
            └── hello-2mghwo7kpinkd
                ├── s-gew0usabs3-e611k.lock
                └── s-gew0usabs3-e611k-n9jek53tv1vs
                    ├── 1d6crpaiajeebzfe.o
                    ├── 3a44f156fv0rzb76.o
                    ├── 3g9kzsj53phza7ii.o
                    ├── 42jn790wo4cvbi0y.o
                    ├── 48bco2yrw0xezka8.o
                    ├── 54y1yn6ksdtd3wa1.o
                    ├── 5doja4y44nwg3ez0.o
                    ├── 5dxeof03oiet4swm.o
                    ├── dep-graph.bin
                    ├── query-cache.bin
                    └── work-products.bin

9 directories, 20 files
Исполнимый файл:

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

olej@R420:~/hello$ ./target/debug/hello 
Hello, world!

olej@R420:~/hello$ ls -l ./target/debug/hello 
-rwxrwxr-x 2 olej olej 3898296 окт 28 16:39 ./target/debug/hello
Сборка динамическая:

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

olej@R420:~/hello$ ldd ./target/debug/hello 
	linux-vdso.so.1 (0x00007ffea3172000)
	libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fbf643ad000)
	libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fbf6438a000)
	libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fbf64384000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbf64192000)
	/lib64/ld-linux-x86-64.so.2 (0x00007fbf64440000)
Из книги:
Имеющийся в Rust инструмент под названием cargo предоставляет как систему
сборки, так и диспетчер пакетов. То есть, cargo знает, как превратить ваш Rust-код
в исполняемые двоичные файлы, а также может управлять процессом загрузки и
компиляции проектных зависимостей.
cargo new создает для вас проект, который построен по стандартному шаблону.
Создание проекта с помощью Cargo
Cargo ожидает, что ваши исходные файлы находятся внутри каталога src. Каталог верхнего уровня проекта предназначен только для файлов README, информации о лицензии, файлы конфигурации и чего то ещё не относящего к вашему коду. Использование Cargo помогает организовывать проект. Есть место для всего и все находится на своём месте.

Если вы начали проект без использования Cargo, как мы делали для "Hello, world!" проекта, то можно конвертировать его в проект с использованием Cargo. Переместите код в подкаталог src и создайте соответствующий файл Cargo.toml в папке.

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

Re: Rust: новый подход к снаряду...

Непрочитанное сообщение Olej » 28 окт 2022, 17:47

Olej писал(а):
28 окт 2022, 16:47
Пойду по этой книге ...
Кроме этой книги есть отличное руководство по языку на самом сайте проекта Rust, от авторов проекта ... и даже его перевод для более беглого знакомства - ссылку показывал выше:
Olej писал(а):
27 окт 2022, 20:24
Язык программирования Rust (перевод)
Выше было сделано:
Olej писал(а):
28 окт 2022, 16:47
Создаю проект (на любом пути):
А теперь точно то же самое, но ручной компиляцией кода Rust без создания проекта - все в точности те же файлы в том же каталоге:

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

olej@R420:~/hello$ pwd
/home/olej/hello

olej@R420:~/hello$ ls src/
main.rs
Компиляция-сборка:

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

olej@R420:~/hello$ rustc src/main.rs

olej@R420:~/hello$ ls -l main
-rwxrwxr-x 1 olej olej 3887960 окт 28 17:40 main

olej@R420:~/hello$ ./main
Hello, world!
Если напечаталось Hello, world!, то примите наши поздравления! Вы написали программу на Rust, что делает вас Rust программистом — добро пожаловать!

Ответить

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

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

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