161390117 © Rolando Mayo | Dreamstime.com
Dreamstime L 161390117 Promo

Reading Rust for C Programmers

March 11, 2022
Here’s a very short intro to the syntax for Rust, the up-and-coming programming language in the embedded space.

This article is part of TechXchange: Rusty Programming

What you’ll learn

  • Some basic Rust syntax.
  • Differences that exist between Rust and C/C++.

Rust is the rising darling in the safe and secure programming arena. The challenge these days is that it’s changing as we speak, which will create havoc on embedded applications—especially those that require long-term support. It will likely join Ada, C, and C++ in the future as it continues to be refined. That’s why it’s good idea to get to know Rust’s features, such as its memory management and approach to object-oriented programming.

Those are both major topics that I will push off to later articles. Their details are a bit more complex than what I want to do here, which is talk about some basic syntax that makes reading Rust code easier for the Rust novice.

Below is a short, runnable Rust program to generate Fibonnaci numbers. It highlights some interesting aspects of Rust that tend to be skipped when presenting Rust for the first time:

fn print_fib_1(n: usize) {
    println!("Fibonacci 1");
    let mut x = (1, 1);
    for i in 0..n {
        println!("{}: {}", i, x.0);
        x = (x.1, x.0 + x.1)
    }
}

fn print_fib_2( arr: &mut [i32]) {
    println!("Fibonacci 2");
    arr[0] = 1;
    arr[1] = 1;
    let n = arr.len();

    for i in 2..n {
        arr[i] = arr[i-1] + arr[i-2];
    }

    for i in 0..n {
        println!("{}: {}", i, arr[i]);
    }
}

fn main() {
    const NUMBER: usize = 5;
    println!("Hello, Fibonacci!");
    print_fib_1(NUMBER);

    let mut x:[i32; NUMBER] = [0; NUMBER];
    print_fib_2(&mut x);
}

The fn keyword introduces a function or procedure. There’s additional syntax for function return values, but that’s for another time. The argument, n, is of type usize.

Now for the interesting part. The println! for printing is actually a macro named println. The exclamation point indicates that a macro is being invoked. Also, macros can have a variable number of arguments, while a function has a fixed number. The brackets in the format string, {}, are placeholders. 

Rust supports tuples, i.e. (1, 1), that contain heterogenous elements, while arrays have homogenous elements. Both are fixed-length items; it’s possible to get the length, i.e., arr.len(). The range, i.e., 0..n, in the for loop are a syntax common to other languages. The array element access looks like arr[i], while the tuple elements are x.1.

The let statement binds a value to a variable. The mut keyword indicates that the variable is mutable, which is the default for Ada, C, and C++. Note: Non-mutable and constants are different. A non-mutable is one that the program can’t change at this point.

I should also talk about this function argument: arr: &mut [i32]. The ampersand indicates a reference that in this case is to an array of type i32 that changed. On the other hand, const is used to define a constant that must be written as an upper-case name like NUMBER.

Finally, we have something that looks like this:

let mut x:[i32; NUMBER] = [0; NUMBER];

This defines an array x that has NUMBER of elements of type i32. The assigned value is an array of 0s. Of course, the code that’s generated will allocate the array in the stack and fill it with zeros before proceeding.

There are a lot of new ideas in Rust, or ones that look different than in other languages. Knowing what you’re looking at will help garner a better understanding of Rust when you start coding. I hope this helps.

Read more articles in the TechXchange: Rusty Programming

Sponsored Recommendations

What are the Important Considerations when Assessing Cobot Safety?

April 16, 2024
A review of the requirements of ISO/TS 15066 and how they fit in with ISO 10218-1 and 10218-2 a consideration the complexities of collaboration.

Wire & Cable Cutting Digi-Spool® Service

April 16, 2024
Explore DigiKey’s Digi-Spool® professional cutting service for efficient and precise wire and cable management. Custom-cut to your exact specifications for a variety of cable ...

DigiKey Factory Tomorrow Season 3: Sustainable Manufacturing

April 16, 2024
Industry 4.0 is helping manufacturers develop and integrate technologies such as AI, edge computing and connectivity for the factories of tomorrow. Learn more at DigiKey today...

Connectivity – The Backbone of Sustainable Automation

April 16, 2024
Advanced interfaces for signals, data, and electrical power are essential. They help save resources and costs when networking production equipment.

Comments

To join the conversation, and become an exclusive member of Electronic Design, create an account today!