Stránky

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Tuesday, May 31, 2016

Programming in Rust - Part 1:Modules and Libraries

After a few years of Java development it's time to look for interesting features new languages can offer. Choice came down to Go, Erlang/Elixir and Rust. I'll talk about how I came to these three in another post. For now it is important to note that my personal favorite is Rust.

Tutorial will be written as a diary while developing simple and/or trivial projects. I'll not cover Rust syntax. Rust programming language has really excellent tutorial at Rust book.

Modules vs Libraries


First lesson is to understand how Rust splits code into logical parts. Rust has source files (*.rs), modules and libraries - known as crates in rust terminology. I have come into confusion over Rust keywords related to usage of libraries and modules.

First create basic Rust project. We will use Cargo a build system which comes as part of a Rust install package.

Dedicate some directory to your Rust projects and within this directory create new Rust library project.

> cargo new mylib
> cd mylib/src

Inside created project you'll find src directory with lib.rs file. Cargo uses lib.rs as root module for library project, and main.rs for executable project. We'll create new executable root main.rs and two module files. This way we can experiment with modules and libraries within one project.

> touch main.rs
> touch moda.rs
> touch modb.rs
> cd ..
Insert following content into main.rs.

// file: src/main.rs
fn main() {
    println!("Hello World!");
}
Run application by:

> cargo run