title | slug |
---|---|
Functions (02) |
functions-02 |
Functions are the first line of organization in any program.
fn main() {
greet(); // Do one thing
ask_location(); // Do another thing
}
fn greet() {
println!("Hello!");
}
fn ask_location() {
println!("Where are you from?");
}
We can add unit tests in the same file.
fn main() {
greet();
}
fn greet() -> String {
"Hello, world!".to_string()
}
#[test] // Test attribute indicates this is a test function
fn test_greet() {
assert_eq!("Hello, world!", greet())
}
// 💡 Always put test functions inside a tests module with #[cfg(test)] attribute.
// cfg(test) module compiles only when running tests. We discuss more about this in the next section.
💭 An attribute is a general, free-form metadatum that is interpreted according to name, convention, and language and compiler version.