Basic data types

Here are the basic data types in C++ (64bit) and Rust

C++ Rust
int i32
short i16
long i64
char i8
unsigned int u32
unsigned short u16
unsigned long u64
unsigned char u8
size_t usize
float f32
double f64
bool bool
char* &str
std::string String

A C++ (64bit) example with basic data types:

#include <string>

using namespace std;
int main()
{
    int a = -100000;
    short b = -10000;
    long c = -1000000000000l;
    char d = -100;
    unsigned int e = 200000;
    unsigned short f = 20000;
    unsigned long g = 2000000000000l;
    unsigned char h = 200;
    size_t k = 100;
    float l = 3.14;
    double m = 3.141592654;
    bool n = true;
    char* s = (char*)"Hello";
    string st = s;
}

The Rust program :

fn main()
{
    let a : i32 = -100000;
    let b : i16 = -10000;
    let c : i64 = -1000000000000i64;
    let d : i8 = -100;
    let e : u32 = 200000;
    let f : u16 = 20000;
    let g : u64 = 2000000000000u64;
    let h : u8 = 200;
    let k : usize = 100;
    let l : f32 = 3.14;
    let m : f64 = 3.141592654;
    let n : bool = true;
    let s : &str = "Hello";
    let st : String = s.to_owned();
}

Similar to C++, Rust has two type of string data types : the raw string &str, which is used to encode a sequence of utf-8 characters and therefore is somehow equivalent to char* in C++, and the object String, which is similar to std::string in C++. The method to_owned is used to convert a raw string to an object string.

Rust can infer data types for variables based on the value assigned to them at initialization, so there is no need for explicit declaration of data types (this is similar to the use of auto in modern C++) :

fn main()
{
    let a = -100000i32;
    let b = -10000i16;
    let s = "Hello";
    let st = s.to_owned();
}

Variables in Rust are immutable by default. If a variable needs to change value during runtime, it needs to be declared as mutable with keyword mut

fn main()
{
    let a = -100000i32;
    let mut b = -10000i16;
    // a = 100000;         // error, cannot change value of immutable variable
    b += 100;              // ok, since b is mutable
}

results matching ""

    No results matching ""