Book Image

Rust Essentials

By : Ivo Balbaert
Book Image

Rust Essentials

By: Ivo Balbaert

Overview of this book

<p>Starting by comparing Rust with other programming languages, this book will show you where and how to use Rust. It will discuss primitive types along with variables and their scope, binding and casting, simple functions, and ways to control execution flow in a program.</p> <p>Next, the book covers flexible arrays, vectors, tuples, enums, and structs. You will then generalize the code with higher-order functions and generics applying it to closures, iterators, consumers, and so on. Memory safety is ensured by the compiler by using references, pointers, boxes, reference counting, and atomic reference counting. You will learn how to build macros and crates and discover concurrency for multicore execution.</p> <p>By the end of this book, you will have successfully migrated to using Rust and will be able to use it as your main programming language.</p>
Table of Contents (17 chapters)
Rust Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Interfacing with C


Due to the vast functionality that exists in C's code, it can sometimes be useful to delegate processing to a C routine, instead of writing everything in Rust.

You can call all functions from the C standard library by using the libc crate, which must be obtained through Cargo. To do this, simply add the following to your Rust code:

#![feature(libc)]
extern crate libc;

To import C functions and types, you can sum them up like this:

use libc::{c_void, size_t, malloc, free};

Alternatively, you can use a * wildcard, such as use libc::*;, to make them all available.

To work with C (or another language) from Rust, you will have to use the FFI, which has its utilities in the std::ffi module.

Here is a simple example to call C for printing out a Rust string with the puts function in C:

// code from Chapter 9/code/calling_libc.rs:
#![feature(libc)]
extern crate libc;
use libc::puts;
use std::ffi::CString;

fn main() {
  let sentence = "Merlin is the greatest magician!";
  let to_print...