fn print_length(s: &String) {
println!("The length of '{:?}' is: {}", s, s.len());
}
let s1 = "Static string";
print_length( /* ??? */ );
let s2 = String::from("Heap-allocated string");
print_length( /* ??? */ );
let s3 = &s2[14..];
print_length( /* ??? */ );
fn print_length(s: &String) {
println!("The length of '{:?}' is: {}", s, s.len());
}
let s1 = "Static string"; // => &str
print_length(&String::from(s1));
let s2 = String::from("Heap-allocated string"); // => String
print_length(&s2);
let s3 = &s2[14..]; // => &str
print_length(&String::from(s3));
fn print_length(s: &str) {
println!("The length of '{:?}' is: {}", s, s.len());
}
let s1 = "Static string";
print_length( /* ??? */ );
let s2 = String::from("Heap-allocated string");
print_length( /* ??? */ );
let s3 = &s2[14..];
print_length( /* ??? */ );
fn print_length(s: &str) {
println!("The length of '{:?}' is: {}", s, s.len());
}
let s1 = "Static string"; // => &str
print_length(s1);
let s2 = String::from("Heap-allocated string"); // => String
print_length(&s2[..]);
print_length(&s2);
let s3 = &s2[14..]; // => &str
print_length(s3);
fn print_length(l: &[u32]) {
println!("The length of '{:?}' is: {}", l, l.len());
}
let l1 = [1_u32, 2, 3, 4];
print_length( /* ??? */ );
let l2 = vec![1_u32, 2, 3, 4];
print_length( /* ??? */ );
let l3 = &l2[0..2]; // => &[u32]
print_length( /* ??? */ );
fn print_length(l: &[u32]) {
println!("The length of '{:?}' is: {}", l, l.len());
}
let l1 = [1_u32, 2, 3, 4]; // => [u32; 4];
print_length(&l1);
let l2 = vec![1_u32, 2, 3, 4]; // => Vec<u32>
print_length(&l2);
let l3 = &l2[0..2]; // => &[u32]
print_length(l3);
&String
→ some_func(&str)
&Vec<u32>
→ some_func(&[u32])
println!("{}² + {}² = {}²", 3, 4, 5);
print!("{}² + {}² = {}²\n", 3, 4, 5);
let s = format!("{}² + {}² = {}²", 3, 4, 5);
Въпрос: какво смятате, че е s?
&'static str
&str
&String
String
let s = format!("{}² + {}² = {}²", 3, 4, 5);
&'static str
→ НЕ. Има динамични данни.
&str
, &String
→ НЕ. Кой е owner?
String
→ ДАcargo new communicator
mod network {
fn connect() {
// ...
}
}
mod client {
fn connect() {
// ...
}
}
::
(за външни пакети, communicator::
)
network
, client
connect
network::connect()
client::connect()
mod network {
fn connect() {
// ...
}
mod client {
fn connect() {
// ...
}
}
}
network::connect()
network::client::connect()
mod network {
fn connect() { /* ... */ }
mod client {
fn connect() { /* ... */ }
fn init() {
// извикваме `network::client::connect()`
connect();
// client::connect() // грешка при компилация
}
}
}
mod network {
fn connect() { /* ... */ }
mod client {
fn connect() { /* ... */ }
fn init() {
// извикваме `network::connect()`
::network::connect();
super::connect();
// network::connect() // грешка при компилация
}
}
}
mod network {
fn connect() { /* ... */ }
fn init() {
// извикваме `network::connect()`
connect();
::network::connect();
}
mod client {
fn connect() { /* ... */ }
}
}
mod network {
fn connect() { /* ... */ }
fn init() {
// извикваме `network::client::connect()`
client::connect(); // ?
::network::client::connect(); // ?
}
mod client {
fn connect() { /* ... */ }
}
}
error[E0603]: function `connect` is private --> src/main.rs:12:9 | 12 | client::connect(); | ^^^^^^^^^^^^^^^
mod network {
fn connect() { /* ... */ }
fn init() {
// извикваме `network::connect()`
client::connect();
::network::client::connect();
}
mod client {
// добавяме pub
pub fn connect() { /* ... */ }
}
}
mod network {
mod client {
pub fn connect() {
log_debug_statement();
}
fn log_debug_statement() {
println!("client::connect()");
}
}
}
mod network {
mod client {
pub fn connect() {
log_debug_statement();
}
fn log_debug_statement() {
println!("client::connect()");
}
}
}
fn main() {
network::client::connect(); // ?
}
pub mod network {
pub mod client {
pub fn connect() {
log_debug_statement();
}
fn log_debug_statement() {
println!("client::connect()");
}
}
}
fn main() {
network::client::connect();
}
mod client {
fn connect() { /* ... */ }
}
mod network {
fn connect() { /* ... */ }
mod server {
fn connect() { /* ... */ }
}
}
communicator ├── client └── network └── server
communicator/ ├── src/main.rs ├── src/lib.rs ├── src/client.rs └── src/network/ ├── mod.rs └── server.rs
src/lib.rs
pub mod client;
pub mod network;
src/client.rs
// ::client::connect()
pub fn connect() {
log_debug_statement();
}
fn log_debug_statement() {
println!("client::connect()");
}
src/network/mod.rs
pub mod server;
// ::network::connect()
pub fn connect() {
}
src/network/server.rs
// ::network::server::connect()
pub fn connect() {
}
src/main.rs
fn main() {
client::connect();
network::connect();
network::server::connect();
}
От външен проект:
extern crate communicator;
fn main() {
communicator::client::connect();
communicator::network::connect();
communicator::network::server::connect();
// communicator::client::log_debug_statement() // => compile-time грешка
}
extern crate communicator;
use communicator::client;
use communicator::network;
fn main() {
client::connect();
network::connect();
network::server::connect();
}
extern crate communicator;
use communicator::{client, network};
fn main() {
client::connect();
network::connect();
network::server::connect();
}
extern crate communicator;
use communicator::client;
use communicator::{self, server};
fn main() {
client::connect();
network::connect();
server::connect();
}
extern crate communicator;
use communicator::client::connect;
use communicator::network::connect;
// грешка при компилация
extern crate communicator;
use communicator::client::connect as client_connect;
use communicator::network::connect as network_connect;
#[test]
fn test_something() {
// ...
}
#[derive(Debug, Clone)]
struct User {
// ...
}
Някои примери за условна компилация
#[cfg(target_os = "macos")]
struct Client;
#[cfg(any(foo, bar))]
fn bark() { /*...*/ }
#[cfg(all(unix, target_pointer_width = "32"))]
impl Cat {}
#[cfg(not(foo))]
{
// ...
}
Атрибут `doc`
#![doc="Hello World"]
#[doc="Hello World"]
//! A contiguous growable array type with heap-allocated contents, written
//! `Vec<T>`.
//!
//! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
//! `O(1)` pop (from the end).
//!
//! # Examples
//!
//! You can explicitly create a [`Vec<T>`] with [`new`]:
//!
//! ```
//! let v: Vec<i32> = Vec::new();
//! ```
/// A UTF-8 encoded, growable string.
///
/// The `String` type is the most common string type that has ownership over the
/// contents of the string. It has a close relationship with its borrowed
/// counterpart, the primitive str.
pub struct String {
vec: Vec<u8>,
}
pub struct String {
/// Some field comment
vec: Vec<u8>, /// This does not work
}
impl String {
/// Creates a new empty `String`.
///
/// Given that the `String` is empty, this will not allocate any initial
/// buffer. While that means that this initial operation is very
/// inexpensive, but may cause excessive allocation later, when you add
/// data. If you have an idea of how much data the `String` will hold,
/// consider the [`with_capacity`] method to prevent excessive
/// re-allocation.
pub fn new() -> String {
String { vec: Vec::new() }
}
}
rustdoc
cargo doc
The Rustdoc Book
cargo test
пуска всички тестове на проекта
cargo test --help
за повече информация#[cfg(test)]
mod tests {
#[test]
fn it_works() {
// ...
}
}
assert!()
assert_eq!()
assert!(1 == 2);
assert_eq!(1, 2);
project ├── src └── tests └── some_test.rs
tests
extern crate project
/// A string.
///
/// # Examples
///
/// ```
/// let s = String::new();
/// ```
struct String;
fn main() {}
обвивка около теста
#
в началото на реда го скрива при генериране на документацията```ignore
```no_run
for element in collection.into_iter() {
//...
}
for element in collection.iter() {
//...
}
for element in collection.iter_mut() {
//...
}
for element in collection.bytes() {
//...
}
for element in collection.chars() {
//...
}