#[derive(Eq, PartialEq, Debug)] (1)
pub struct Point { (2)
x: i32,
y: i32,
}
Some collected hints to get you started.
#[derive(Eq, PartialEq, Debug)] (1)
pub struct Point { (2)
x: i32,
y: i32,
}
1 | Derives allow to generate some standard functionality |
2 | Any type can carry a visibility modifier to export them |
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p); (1)
println!("{:#?}", p); (2)
}
1 | Debug makes the Debug formatting string work |
2 | There’s also a more structured version, also enabled through it |
#[derive(Eq,PartialEq,Debug)] (1) (2)
struct Point {
x: i32, (3)
y: i32,
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 1, y: 2 };
if p1 == p2 { (4)
println!("The same!");
}
assert_eq!(p1, p2); (5)
}
1 | Eq describes total equality: for every pair of values, equality is defined |
2 | PartialEq is enough for getting == |
3 | Both can only be derived if all inner fields are both |
4 | Equality in action! |
5 | The assert_eq! compares to values and panics if they don’t match! |
If you expect something to work or an item to be there, use unwrap
:
fn main() {
let file: File = File::open("Cargo.toml").unwrap();
}
This expects the operation to have worked. You can add structured error handling later.
Strings and string slices work much the same.
fn main() {
let slice: &str = "Hello world!";
let string: String = String::from(slice);
}
In the beginning, habitually use String
.
struct Owned {
string_data: String
}
fn returns_string() -> String {
String::from("Hello World")
}
fn hello(who: &str) -> String {
format!("Hello, {}!", who)
}
use my_library::my_function; (1)
#[test]
fn my_test() {
assert_eq!(1, 1);
}
#[test]
#[should_fail]
fn failing_test() {
assert_eq!(1, 2);
}
Rust and Cargo allows you to easily provide test for your code.
These can be put either directly in the source file or in any file in tests
.
1 | Only needed when putting files in tests . |
fn addition(a: i32, b: i32) -> i32 {
todo!()
}
#[test]
fn addition_test() {
assert_eq!(addition(1,2), 3);
}