当前位置:网站首页>[rust notes] 06 package and module
[rust notes] 06 package and module
2022-07-03 08:35:00 【phial03】
06 - Packages and modules
6.1 - package
Cargo.tomlThe file can list the package name , And its assigned version number . Used to get .cargo buildThe technique of :--verboseOptions : Understand how packages work together ;--crate-type libOptions : tellrustcDon't look formain()Function execution , It's about generating a.rlibfile , It contains compiled code , Available for laterrustcCommands are used as input .--crate-type binOptions , The compilation result is a binary file .--externOptions : Give the file name of each library used by the current package .--releaseOptions : Generate optimized code , Run faster , But the compilation time will be extended . here , Integer overflow will not be checked , And will skipdebug_assert!()Assertion . meanwhile , The stack trace information generated for surprise is not reliable .
Construction analysis :
Command line Cargo.toml Blocks used cargo build [profile.dev] cargo build --release [profile.release] cargo test [profile.test] If you want to analyze the program , Get the most comprehensive data , Optimization needs to be enabled at the same time (
--releaseOptions , For the release and construction of programs ) And commissioning ( Debug build during development ) Symbol (symbol), Then it must be incargo.tomlAdd the following code to :[profile.release] debug = true # Enable debug tags in the release builddebugSet controlsrustcMedium-gOptions- Execute at this time
cargo build --releaseYou can get a binary file with debugging symbols . - Optimization settings are not affected .
6.2 - modular
The module is Rust The namespace of , Is also a function 、 type 、 Constant, etc Rust The container of a program or library .
- The way to create a module is as follows :
mod mod_name1 { ... } mod mod_name2;Package solves the problem of code sharing between projects , The module solves the problem of code organization in the project .
Modules are feature items (item) Set , By keyword
pubMark public or private feature items , Anything not markedpubAll feature items of are module private .
6.2.1 - Modules and files
- Modules can be created using files , There is no need to add
modStatement . - Modules can also have their own directories . If you call a module
mod test;when , Can checktest.rsfile , It will also check whether there istest/mod.rsfile . If both files exist , Or none of them , Will report a mistake .
6.2.2 - Path and import
::The operator : Features for accessing modules . Reference by absolute path .::std: Start with a double colon , It refers to the top-level module of the standard library .::std::mem: It refers to the sub module of the standard library .::std::mem::swap: It refers to a public function in the module .
useStatement : In the whole code block or the whole module , Import a module or public function .- Supports importing multiple modules at a time :
use std::collections::{HashMap, HashSet};. - Support importing all modules :
use std::io::prelude::*. - Modules do not automatically inherit names from their parent modules . For example module
proteins/mod.rsThere are the following statements in :
// proteins/mod.rs pub enum AminoAcid { ...} pub mod synthesis;- Sub module
proteins/synthesis.rsThe code in , You won't automatically see the typeAminoAcid:
// proteins/synthesis.rs pub fn synthesize(seq: &[AminoAcid]) { // error : Type not found AminoAcid ... } // It is amended as follows : use super::- Supports importing multiple modules at a time :
superkeyword : Represents the parent module of the current module . The above code can be modified as follows :// proteins/synthesis.rs use super::AminoAcid; pub fn synthesize(seq: &[AminoAcid]) { ... }selfkeyword : Represents the current module .// proteins/mod.rs use self::synthesis::synthesize; use self::AminoAcid::*;Child modules can access private feature items in their parent modules , But you must import each item by name . Use
super::*;Only those markedpubFeature items of
6.2.3 - Standard front module
Standard library
stdIt will be automatically linked to each program , Contains hidden declarationsextern crate std;Especially commonly used names such as :
Vecand
ResultWill be included in the standard Prelude .
std::prelude::vlIt is the only pre module that will automatically paste and import . It includes common features and types .
6.2.4 - Characteristic item
The module consists of characteristic items ,Rust The main characteristic items of are as follows :
function .
type .
- User defined types include
strustStructure 、enumEnumeration andtraitSpecial type .
- User defined types include
Type the alias :
typekeyword , Define an alias for an existing type .type Table = HashMap<String, Vec<String>>;.
implblock :- Add methods to types .
- Not for
implMarkpub, Only individual methods can be marked .
Constant :
constKeywords are used to define constants . AndletThe difference between , It can be marked aspub, And the type must be specified .pub const ROOM_TEMPERATURE: f64 = 20.0;staticKeyword defines static features , Equivalent to constant .pub static ROOM_TEMPERATURE: f64 = 68.0;The value of a constant is compiled into the code wherever it is used .
- Constants in code , It is often used to save magic values and strings .
- Constants do not
mut.
Static variables exist before the program runs , And will continue to exist , Know that the program exits .
- Static variables are in the code , It is often used to save a large amount of data , Or use it to borrow references to constant values .
- Static variables can be marked
mut. Modifiable static variables , Not thread safe in nature , Never use in secure code .
modular :
- Modules can contain sub modules .
- It can be private , It can also be public .
Import :
usekeyword .extern cratekeyword . Import an external library .
externblock :- Declare a collection of functions written in other languages , In order to be in Rust They are called in code .
- If you want to use this block in other packages , Then you need to include this function and even the whole module , Are marked as public .
6.3 - library
The steps of changing the program code into a library :
- Divide the existing project into two parts :
- A package to be called a library , Include all shared code ;
- An executable file , Contains code for use only by existing command-line programs .
- Publish this library :
- take
src/main.rsRename it tosrc/lib.rs. - to
src/lib.rsin , Add items of public type to be called librariespubkeyword . - hold
mainFunctions are temporarily transferred to other places .
- take
- Add :
- By default ,
cargo buildFromsrcFind files in the code directory , Then decide how to create . If you seesrc/lib.rs, Then we know that we need to build a library . src/lib.rsThe code in forms the root module of the Library . Other packages that use this library , Only public features in this root module can be accessed .
- By default ,
6.4-src/bin Catalog
- cargo Will automatically
src/binMedium.rsFile as an additional program to build .
6.5 - attribute
Any feature item is available attribute To modify .
attribute : It is the universal syntax of various instructions and suggestions written for the compiler .
Common attribute skills :
#[allow]attribute : At compile time , Disable some warnings .// At compile time , Will not report about non_camel_case_types Keyword warning #[allow(non_camel_case_types)] pub struct git_revspec { ... }#[cfg]attribute : Compile the condition as a special type :// Include this module only when compiling for Android #[cfg(target_os = "android")] mod mobile;frequently-used
#[cfg]grammar#[cfg(...)]OptionsEnable scene testenable test ( When we use cargo testorrustc --testCompile time )debug_assertionsEnable debug assertion ( Usually used for non optimized builds ) unixby Unix( Include macOS) compile windowsby Windows compile target_pointer_width = "64"in the light of 64 Bit platform . Another possible value is “32” target_arch = "x86_64"in the light of x86-64 framework , Other values are :“x86”、“arm”、“aarch64”、“powerpc”、“powerpc64” and “mips” target_os = "macos"by macOS compile . Other values are “windows”、“ios”、“android”、“linux”、“openbasd”、“netbsd”、“dragonfly” and “bitrig” feature = "robots"Enable user-defined names “robots” Characteristics of ( When we use cargo build --feature robotsorrustc --cfg feature='"robots"'Compile time ). Characteristic in Cargo.toml Of[feature]Partial declarationnot(A)A When not satisfied, two different implementations of a function should be provided , Mark one of them #[cfg(x)], The other is marked#[cfg(not(x))]all(A, B)A and B When it's all satisfied , Equivalent to && any(A, B)A or B When satisfied , Equivalent to ||
#[inline]attribute : Inline extension of function , Do some micro control .- If a function or method is defined in a package , But call in another package , that Rust It will not be extended in the line . Unless it is generic ( There are type parameters ) Or clearly marked
#[inline]. #[inline(always)], Every call is required to extend the function in the line .#[inline(never)], Ask never to internalize .
- If a function or method is defined in a package , But call in another package , that Rust It will not be extended in the line . Unless it is generic ( There are type parameters ) Or clearly marked
#[cfg]and#[allow], Can be added to the entire module , And apply to all of them .#[test]and#[inline], Can only be added to individual feature items .To add attributes to the entire package , Need to be in
main.rsorlib.rsTop of file 、 Add before any feature , And use it#!instead of#Mark .// lib.rs #![allow(non_camel_case_types)] // You can add attributes to the entire feature item , Instead of the subsequent individual characteristic items pub struct git_revspec { ... } pub struct git_error { ... }#![feature]attribute : For opening Rust Unsafe features of languages and libraries . For example, some new testing functions .
6.6 - Testing and documentation
#[test]attribute : Mark up some functions , Indicates that unit tests will be performed .cargo testWill run all#[test]Marked code , And generate test results .Two assertion macros that are often used in testing , It is used to check that there is no deformation (invariant):
assert!(expr)macro : stayexprbytrueWhen it comes to success ; otherwise , Will be surprised and cause the test to fail .assert_eq!(v1, v2)macro : Equivalent toassert!(v1 == v2), But if the assertion fails , Then the error message will show two values .- Even in the release build
assert!andassert_eq!. - have access to
debug_assert!anddebug_assert_eq!, Write assertions that are checked only in debug builds .
Marked as
#[test]The function of will be conditionally compiled .cargo buildorcargo build --releaseWill skip the test code .When there are many unit tests , It is suggested to put it in a
testsIn the module , And use#[cfg]Property declares the entire module for testing purposes only .#[cfg(test)] // Include this module only when testing builds mod tests { ... }Rust By default, multiple tests are run through multiple threads .
cargo test testnameYou can disable multithreading , Then run only one test at a time .
6.6.1 - Integration testing
- Integration testing is placed on
testsIn the directory.rsfile . testsDirectory andsrcPut the catalog together .- Cargo Each integration test will be compiled into a separate package , And link it to your library and Rust test suite .
cargo testYou can run unit tests , Also run integration tests . If you only run specific files ( Such astest/unfurl.rs) Integration testing in , Then you can executecargo test --test unfurl.
6.6.2 - file
cargo docCommand to createHTMLfilecargo doc --no-deps --open--no-depsOptions : send Cargo Generate documents only for the current package , Regardless of the package it depends on .--openOptions : send Cargo After the document is generated , Just open it in the browser .
Cargo Save the newly generated document file in
target/docDirectory .Cargo The generated document is based on
pubSpecial types and their corresponding document annotation generation .#[doc]attribute : Used to mark document comments .///Opening comment , Will be regarded as#[doc]attribute ;/// test Equivalent to #[doc = "test"]//!Opening comment , It will also be regarded as#[doc]attribute , Can be added to the corresponding include feature , Usually in modules or packages .
The content in the document comments will be followed Mardown Parsing .
6.6.3 - Document the test
Rust The code block in the document comment , Automatically convert to test .
/// #Some lines of code can be hidden .no_runannotation : Combine code blocks to define symbols , You can disable testing for specific code blocks ./// ```no_run /// ... /// ```ignoreannotation : Do not want the test code to be compiled ./// ```ignore /// ... /// ```If the document comments are in other languages , Then you need to use the name tag of the language .
/// ```c++ /// ... /// ```
6.7 - Designated dependency
Specified version number :
image = "0.6.1"Appoint Git Warehouse address and revision :
image = { git = "https://github.com/test/test.git", rev = "rust666" }Specify the directory containing the source code of the dependent package :
image = { path = "test/image" }If you find that an open source package is not suitable , Then you can. Fork Come down , And then modify Cargo.toml Just one line of code in the file . Next ,cargo build Will immediately switch to Fork Copied version , Instead of using the official version .
6.7.1 - edition
Version compatibility :
- With
0.0The first version is more original ,Cargo It will not be considered compatible with any other version . - With
0.xThe first version , Will be considered the same as others0.xCompatible versions of . - If the project reaches
1.0edition , Only the new main version will break compatibility .
- With
Support the use of operators to specify versions :
Cargo.toml Writing in Chinese meaning image = “=0.10.0” Use only 0.10.0 edition image = “>=1.0.5” Use 1.0.5 Version or later image = “>1.0.5 <1.1.9” Use greater than 1.0.5 But less than 1.1.9 Version of image = “<=2.7.10” Use less than or equal to 2.7.10 Version of Another strategy for specifying versions is to use wildcards
*( Not commonly used ).
6.7.2-Cargo.lock
Cargo.lockYou can avoid upgrading the dependent version every time you build . Make sure you are on a different machine , Get consistent 、 Reproducible construction .- When building the project for the first time ,Cargo Will output one
Cargo.lockfile , Record the exact version number of each package used by the project . This file will be referred to in subsequent builds , And continue to use the same file . - Only operate in the following Cargo To upgrade :
- Manually modified
Cargo.tomlVersion number in the file - It's running
cargo update: Upgrade to andCargo.tomlThe latest version compatible with the version specified in .
- Manually modified
- If the project is an executable , Then we should put
Cargo.lockSubmit to version control system . Anyone who builds this project , You can get the same version .
6.8-crates.io
cargo packageThe command will create a file (target/package/XXX.0.1.0.crate), It contains all the source files of the Library , as well as Cargo.toml. This file can be uploaded to crates.io, Share with the world .cargo package --listYou can view what files are included .Can be in Cargo.toml Add the following license information to the file ( Sensitive information can be deleted, such as authors The mailbox in ):
[package] name = "test_code" version = "0.1.0" authors = ["You <[email protected]>"] license = "MIT" homepage = "https://www.example.com" repository = "https://gitee.com/test/test_code" documentation = "http://www.example.com/docs" description = """ Test Code. """Log in to crates.io, And get API Secret key ( It needs to be kept secret ), Then execute only on the controllable safe computer :
cargo login ^^&@*&...Finally, execute
cargo publishTo publish the library to crates.io On .
6.9 - working space
Cargo It will ensure that each package has its own build directory :
target, Include a separate build on which this package depends .Cargo working space (workspace): Share the same build directory and
Cargo.lockA package of files . It can save compilation time and disk space .How to create a workspace :
Create a
Cargo.tomlfileAdd the following code to it : among
fern_simAnd so on are the names of subdirectories containing their respective packages .[workspace] members = ["fern_sim", "fern_img", "fern_video"]Put
Cargo.lockDocument andtaergetDelete all directories .After that , Whether running in any package
cargo build, Will automatically create a shared build directory in the root directory , All packages are shared .
cargo build --allThe command will build all packages in the current workspace .cargo testandcargo docAlso support--allOptions .
6.10 - Other content
- When in
crates.ioAfter releasing the open source package on , The package document will be automatically published todocs.rs. - If the project is in Github On ,Travis CI You can push code every time , Automatically build and test . View details (https://travis-ci.org/).
- You can generate a
README.mdfile . Provided by third-party plug-inscargo install readme. Supportcargo readme --helpTo learn this plug-in .
See 《Rust Programming 》( Jim - Brandy 、 Jason, - By orendov , Translated by lisongfeng ) Chapter viii.
Original address
边栏推荐
- UE4 plug in development
- Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
- Transmit pictures with Base64 encoding
- MXone Pro自适应2.0影视模板西瓜视频主题苹果cmsV10模板
- Cesium for unreal quick start - simple scenario configuration
- Some understandings of 3dfiles
- Golang json格式和结构体相互转换
- Initial unity
- Swagger document configuration
- Message queue for interprocess communication
猜你喜欢
![P1596 [USACO10OCT]Lake Counting S](/img/a7/07a84c93ee476788d9443c0add808b.png)
P1596 [USACO10OCT]Lake Counting S

Simply start with the essence and principle of SOM neural network

数据库原理期末复习

Ue5 opencv plug-in use

Visual Studio (VS) shortcut keys

Chocolate installation

Mall management system of database application technology course design

數據庫應用技術課程設計之商城管理系統

C#课程设计之员工信息管理系统

Redis data structure
随机推荐
Unity editor expansion - window, sub window, menu, right-click menu (context menu)
Golang 中string和int类型相互转换
Intersectionpicker in osgearth
C#课程设计之学生教务管理系统
Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB
php-fpm软件的安装+openresty高速缓存搭建
Osgearth starry background
MXone Pro自适应2.0影视模板西瓜视频主题苹果cmsV10模板
使用base64编码传图片
Minimap plug-in
VIM learning notes from introduction to silk skating
Downward compatibility and upward compatibility
[K & R] Chinese Second Edition personal questions Chapter1
Unity notes 1
One dimensional array two dimensional array (sort Max insert sort)
Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
[audio and video] ijkplayer error code
Unity editor expansion - the framework and context of unity imgui
Redis data structure
UE4 source code reading_ Bone model and animation system_ Animation process