Home About Contact

 

Jumpstart to Rust from a background of Swift, PHP, Java….

3 min read

Recently, I’ve got some interest to explore the Blockchain database which I’d need to write some smart contracts by the use of Rust programming language. As someone with a background of a number of programming languages such as Swift, PHP, JS & Java etc, I’ll tend to compare a new programming language that I’m going to learn with the ones that I’m most familiar with, with the hope to learn quicker.

Thus, in my case, I tend to compare Rust with Swift as Swift is the freshest in mind as I love Swift pretty much and also I’ve done a number of iOS devs with the SwiftUI lately during my free time.

A quick intro about Rust is it’s a pretty young open-source programming language that is specifically good for systems programming that focus on speed, memory safety and parallelism etc.

This morning I spent a few hours with my first hands-on self-learning with Rust and along my learning I’ll tend to look for what Swift can do and how Rust can do it. Without too much saying, here are what I’ve got:

Struct – In Swift, we use pretty much of Struct to hold data and model behaviour in the app. The first thing I started to explore with Rust is struct. Below is the comparison of a Swift and a Rust struct.

The Swift Struct:

struct Person {
    var id : String 
    var firstName : String
    var lastName : String
    var age : UInt8
}

// Instantiate a struct in Swift
let person = Person(id : "198282", firstName : "Jane", lastName : "Chan", age: 25)

The Rust struct:

struct Person {
    id : String 
    first_name : String
    last_name : String
    age  : u8 // unsigned 8-bit integer in Rust, max value 255
              // good enough for age, guess no one will live beyond 255
};

// Instantiate a struct in Rust
let person = Person{id : "198282", first_name : String::from("Jane"), last_name : String::from("Chan"), 25};

Things to take note for the above, in Rust, property name of struct should be in snake case, else you’ll get a a warning, as shown in the image below, when hover over it in VS code or when you compile you’ll get warning too :

And so instantiating the struct is by stating its name and then add curly brackets (vs it’s a parentheses or round brackets for Swift) containing the property name and value pairs.

But when supplying the value of a property or variable which is String type, obviously, it’s not as straightforward as Swift, which you can just supply letters in a string literal with the double quote pair.

As in Rust, for a String type you’ll have two types – the &str and the String. A &str is an immutable reference of String, which you cannot change or manipulate it. Whereas a String is what you can change or manipulate. Obviously in Rust, when you have a string literal, then it’s a &str so you’ll need to convert it to String.

There are a few methods available, as below, by using String::from or &str.to_string(), as below:

String::from("I'm a string");

"I'm a string".to_string();

We often use optional properties in Swift struct or class, so when you don’t have to supply their values when instantiating the struct.

struct Person {
   var id : String
   var name : String?
}

let person = Person(id:"H8365gB") // no value is needed for the property "name" 
                                  // when instantiating it as it's optional

In Rust, type Option represents an optional value. So an optional value in Rust must have either Some contains a value or None which does not, as below:

struct Person {
   id : String
   name : Option<String>
}

let person = Person{id:"H8365gB".to_string(), name: None };
let person2 = Person{id:"H8345gA".to_string(), name: Some( "Charlotte Tay".to_string()) };

Array in Rust

Array in Rust must be specified with fixed length and its type. And when initializing an array, Rust requires every element in the array is given a valid value. Such as the code below, a mutable array of i32 (Int 32) with a length of 3 and each element is initialized with a value of 20.

let mut my_array : [i32; 3] = [20;3]; // initialize a mutable of i32 type
                                          // with a fixed length of 3
println!("my_array is {:?}",my_array);

So the above code will print to the console as follows:

my_array is [20, 20, 20]

Since it’s a mutable array (with let mut), then we can change each of its element with a for loop as follows:

for x in 0..3 {
   my_array[x] = ((x as i32) + 1) * 2;// * 2; 
}
println!("my_array :: {:?} ", my_array);

So, what’s printed on the console is as follows:

my_array :: [2, 4, 6]

In Swift, you can create an empty array of a struct type, add element to it later. Such as follows:

var personArray = [Person]()
for i in 0..<13 {
  personArray.append(Person(id: "id-\(i)"))
}
print("personArray::\(personArray)")

In Rust, you'll have to use vec (reminds me of Vector in Java) to do something similar to Swift above as follows:

let mut vec = Vec::new();
for i in 0..13 {
   let id = format!("id-{}",i);
   vec.push(Person{id: id, name: None });
}

println!("persons in vec :: {:?}", vec);

Think I'm going to love it. But still need to spend some more time to master it, currently, I'm just a beginner. My first day of learning Rust repo is on GitHub

Spread the love
Posted on August 28, 2021 By Christopher Chee

Please leave us your comments below, if you find any errors or mistakes with this post. Or you have better idea to suggest for better result etc.


Our FB Twitter Our IG Copyright © 2024