Skip to content

Latest commit

 

History

History

4_mod

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Learn how organize code

Our cli have two functionalities (greetings and chifoumi)
It is always better to split logic in different files

🎯 Objectives

  • use modules

Organize code in modules

Modules and use Let you control the organization, scope, and privacy of paths

Let split our code in differents files

|-src
  |- main.rs
  |- greetings.rs
// greetings.rs
pub fn greets(name: &str) {
    println!("Hello, {} 🦀 !", name);
}

Nb: functions are private by defaut, you must add pub keyword

// main.rs
use std::env;

mod greetings; //declare module 
use greetings::greets; // import function

fn main() {
    let args: Vec<String> = env::args().collect();

    let name = args.get(1).expect("Name is required");
    greets(&name);
}

📌 Remember

  • declare module and declare usage
  • visibibility is private by default

📚 More resources

📝 Exercice: Split app in different modules

Expected tree

|-src
  |- main.rs
  |- greetings.rs
  |- chifoumi.rs

💡 Tips

  • do not forget visiblity

👏 Congrats

you understand how to organize code in modules

Check a solution with unit tests here

📝 Summary

What you have learned

  • modules
  • visibility

Next Part

🤙 Go to next part: Clap