DEV Community

Michael Olayemi
Michael Olayemi

Posted on

Rust Project for Beginner: Natural Language Detector

Rust is a lovely language, the more you learn it the more you love it. In this tutorial we are going to build a simple application that have the capacity to detect over 80 languages.
This tutorial showcase the following concept in rust:

  • Using external crate in our project
  • Creating functions in rust
  • Using of macros
  • Calling functions in rust

To get starter open your terminal and run the command:cargo init langdector If you don't have rust installed on your system, please head over to the official documentation.

Open the generated project in your vscode or your favourite IDE. Edit the cargo.toml file by adding this dependency:whatlang = "0.13.0.

After adding the external create, we can proceed to our main.rs and begin applying the logic.

We are going to create a function called what_language. With the following codes:

//calling the external crate
use whatlang::{detect, Lang, Script};

//creating a function
fn what_language(mut x: String) {
    let text = &x;
//using .unwrap() for exception handling
    let info = detect(text).unwrap();
//println! is one of the major macros used in rust
    println!("Language type {}", info.lang());
    println!("Language Script {}", info.script());
    println!("System confidence {}", info.confidence());
    println!("System reliability {}", info.is_reliable());

}

fn main() {
//creating string alice
    let alice = String::from(
        "Ĉu vi ne volas eklerni Esperanton? Bonvolu! Estas unu de la plej bonaj aferoj!",
    );
//calling the function
    what_language(alice);
}

Enter fullscreen mode Exit fullscreen mode

The output :

Language type Esperanto
Language Script Latin
System confidence 1
System reliability true
Enter fullscreen mode Exit fullscreen mode

The comments explained each logic._ &x_ obeys the concept of ownership and borrowing.

You can try to run the code :)

Head over to github for the code.
You can follow me of twitter for collaboration.

Top comments (0)