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

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

About the Author

William G. Wong | Senior Content Director - Electronic Design and Microwaves & RF

I am Editor of Electronic Design focusing on embedded, software, and systems. As Senior Content Director, I also manage Microwaves & RF and I work with a great team of editors to provide engineers, programmers, developers and technical managers with interesting and useful articles and videos on a regular basis. Check out our free newsletters to see the latest content.

You can send press releases for new products for possible coverage on the website. I am also interested in receiving contributed articles for publishing on our website. Use our template and send to me along with a signed release form. 

Check out my blog, AltEmbedded on Electronic Design, as well as his latest articles on this site that are listed below. 

You can visit my social media via these links:

I earned a Bachelor of Electrical Engineering at the Georgia Institute of Technology and a Masters in Computer Science from Rutgers University. I still do a bit of programming using everything from C and C++ to Rust and Ada/SPARK. I do a bit of PHP programming for Drupal websites. I have posted a few Drupal modules.  

I still get a hand on software and electronic hardware. Some of this can be found on our Kit Close-Up video series. You can also see me on many of our TechXchange Talk videos. I am interested in a range of projects from robotics to artificial intelligence. 

Sponsored Recommendations

Comments

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