cargo new my_app
my_app/
├── src/
│ └── main.rs
└── Cargo.toml
cargo new --lib my_library
my_library/
├── src/
│ └── lib.rs
└── Cargo.toml
Use tests!
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
#[test]
assert!
, assert_eq!
, assert_ne!
for assertionsassert_eq!
, assert_ne!
will show you the difference between left and right argumentscargo test
will run all testsstruct Point(i32, i32);
fn main() {
let p = Point (1, 2);
assert_eq!(p, Point(1, 2));
}
Errors:
==
cannot be applied to type Point
"Point
doesn't implement Debug
"#[derive(Debug, PartialEq)]
struct Point(i32, i32);
fn main() {
let p = Point (1, 2);
assert_eq!(p, Point(1, 2));
}
Debug
Allows printing of values with debug formatting
#[derive(Debug)]
struct Point { x: i32, y: i32 }
#[derive(Debug)]
struct TuplePoint(i32, i32);
fn main() {
let p = Point { y: 2, x: 1 };
let tp = TuplePoint (1, 2);
println!("{:?}", p); // Point { x: 1, y: 2 }
println!("{:?}", tp); // TuplePoint (1, 2)
}
PartialEq
==
and !=
)PartialEq
, tooPartialEq
and Eq
Eq
means strict mathematical equality:
a == a
should always be truea == b
means b == a
a == b
and b == c
means a == c
IEEE 754 floating point numbers (f32
and f64
) break the first rule (NaN == NaN
is always false). They are PartialEq
and not Eq
.
PartialOrd
and Ord
PartialEq
and Eq
, but they also allow other comparisons (<
, <=
, >=
, >
).Ord
, except f32
and f64
."aaa" < "b"
, but "aaa" > "a"
PartialOrd
or Ord
Debug
, PartialEq
, Eq
, etc. are simultaneously names of "Traits" and names of "derive macros".Debug
and Display
Debug
is for debug printingDisplay
is for user-facing printingprintln!("{:?}", value); // uses `Debug`
println!("{:#?}", value); // uses `Debug` and pretty-prints structures
println!("{}", value); // uses `Display`
Traits can depend on each other.
Eq
and PartialOrd
both require PartialEq
.Ord
requires both Eq
and PartialOrd
#[derive(Debug, Ord)] // will give an error
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] // Ok
Hash
- a type can be used as a key for HashMap
Default
- a type gets a default()
method to produce a default value0
is used for numbers, ""
for stringsOption
fields will be None
Clone
adds a clone()
method to produce a deep copy of a valuederive
lists can get be pretty long.
///
marks doc commentsrustfmt
is a default Rust formatter
cargo fmt
Clippy
is a linter for Rust code
cargo clippy