HomeLinuxRust Fundamentals Sequence #3: Knowledge Varieties in Rust

Rust Fundamentals Sequence #3: Knowledge Varieties in Rust


Within the earlier publish concerning the Rust programming language, we checked out variables, constants and shadowing.

It is just pure to cowl knowledge sorts now.

What are knowledge sorts?

Change the order of those phrases and also you get your reply; “knowledge sorts” -> “sort of knowledge”.

The pc shops knowledge as 0s and 1s however to make sense of it when studying, we use knowledge sort to say what these 0s and 1s imply.

Rust has two kinds of knowledge sorts:

  1. Scalar knowledge sort: Varieties that retailer solely a single worth.
  2. Compound knowledge sort: Varieties that retailer a number of values, even values of various sorts.

On this article, I shall cowl scalar knowledge sorts. I’ll undergo the second class within the subsequent article.

Following is a quick overview of the 4 principal classes of Scalar knowledge sorts in Rust:

  • Integers: Shops entire numbers. Has sub-types for every particular use case.
  • Floats: Shops numbers with a fractional worth. Has two sub-types based mostly on measurement.
  • Characters: Shops a single character of UTF-8 encoding. (Sure, you possibly can retailer an emoji* in a personality.)
  • Booleans: Shops both a true or a false. (For builders who cannot agree if 0 is true or if 0 means false.)

Integers

An integer within the context of a programming language refers to entire numbers. Integers in Rust are both Signed or Unsigned. Unsigned integers retailer solely 0 and optimistic numbers, whereas Signed integers can retailer adverse numbers, 0 and optimistic numbers.

💡

The vary of Signed integers begins from -(2n-1) and this vary ends with (2n-1)-1. Likewise, the vary for Unsigned integers begins at 0 and ends with (2n)-1.

Following are the out there Integer sorts based mostly on the signal and size:

Integer data types in Rust

As you possibly can see, Rust has Signed and Unsigned integers of size 8, 16, 32, 64 and even 128!

The integers with *measurement fluctuate based mostly on the structure of the pc. On 8-bit micro-controllers, it’s *8, on 32-bit legacy computer systems, it’s *32 and on fashionable 64-bit programs, it’s *64.

The usage of *measurement is to retailer knowledge that’s principally associated to reminiscence (which is machine dependent), like pointers, offsets, and so on.

💡

When you don’t explicitly specify a subset of the Integer sort, the Rust compiler will infer it is sort to be i32 by default. Clearly, if the worth is larger or smaller than what i32 can maintain, the Rust compiler will politely error out and ask you to manually annotate the sort.


Rust not solely permits you to retailer integers of their decimal kind but additionally within the binary, octal and hex kinds too.

For higher readability, you need to use underscore _ as a alternative for commas in writing/studying large numbers.

fn principal() {
    let bin_value = 0b100_0101; // use prefix '0b' for Binary illustration
    let oct_value = 0o105; // use prefix '0o' for Octals
    let hex_value = 0x45; // use prefix '0x' for Hexadecimals
    let dec_value = 1_00_00_000; // similar as writing 1 Crore (1,00,00,000)

    println!("bin_value: {bin_value}");
    println!("oct_value: {oct_value}");
    println!("hex_value: {hex_value}");
    println!("dec_value: {dec_value}");
}

I’ve saved the decimal quantity 69 in binary kind, octal kind and hexadecimal kind within the variables bin_value, oct_value and hex_value respectively. Within the variable dec_value, I’ve saved the quantity 1 Crore (10 million) and have commas with underscores, as per the Indian numbering system. For these extra acquainted with the Worldwide numbering system, it’s possible you’ll write this as 10_000_000.

Upon compiling and operating this binary, I get the next output:

bin_value: 69
oct_value: 69
hex_value: 69
dec_value: 10000000

Floating level numbers

Floating level numbers, or extra generally referred to as “float(s)” is an information sort that holds numbers which have a fractional worth (one thing after the decimal level).

Not like the Integer sort in Rust, Floating level numbers have solely two subset sorts:

  • f32: Single precision floating level sort
  • f64: Double precision floating level sort

Just like the Integer sort in Rust, when Rust infers the kind of a variable that looks like a float, it’s assigned the f64 sort. It’s because the f64 sort has extra precision than the f32 sort and is sort of as quick because the f32 sort in most computational operations. Please observe that each the floating level knowledge sorts (f32 and f64) are Signed.

📋

The Rust programming language shops the floating level numbers as per the IEEE 754 normal of floating level quantity illustration and arithmetic.
fn principal() {
    let pi: f32 = 3.1400; // f32
    let golden_ratio = 1.610000; // f64
    let 5 = 5.00; // decimal level signifies that it should be inferred as a float
    let six: f64 = 6.; // even the although sort is annotated, a decimal level remains to be
                       // **obligatory**

    println!("pi: {pi}");
    println!("golden_ratio: {golden_ratio}");
    println!("5: {5}");
    println!("six: {six}");
}

Look carefully on the 5th line. Though I’ve annotated the sort for the variable six, I want to a minimum of use the decimal level. When you have one thing after the decimal level is as much as you.

The output of this program is fairly predictable… Or is it?

pi: 3.14
golden_ratio: 1.61
5: 5
six: 6

Within the above output, you might need seen that whereas displaying the worth saved inside variables pi, golden_ratio and 5, the trailing zeros that I specified on the time of variable declaration, are lacking.

Whereas these zeros should not eliminated, they’re omitted whereas outputting the values by way of the println macro. So no, Rust didn’t tamper along with your variable’s values.

Characters

You’ll be able to retailer a single character in a variable and the sort is just char. Like conventional programming languages of the ’80s, you possibly can retailer an ASCII character. However Rust additionally extends the character sort to retailer a legitimate UTF-8 character. This implies that you could retailer an emoji in a single character 😉

💡

Some emojis are a mixture of two current emojis. An excellent instance is the ‘Fiery Coronary heart’ emoji: ❤️‍🔥. This emoji is constructed by combining two emojis utilizing a zero width joiner: ❤️ + 🔥 = ❤️‍🔥

Storing such emojis in a single Rust variable of the character sort shouldn’t be doable.

fn principal() {
    let a="a";
    let p: char="p"; // with express sort annotation
    let crab = '🦀';

    println!("Oh look, {} {}! :{}", a, crab, p);
}

As you possibly can see, I’ve saved the ASCII characters ‘a’ and ‘p’ inside variables a and p. I additionally retailer a legitimate UTF-8 character, the crab emoji, within the variable crab. I then print the characters saved in every of those variables.

Following is the output:

Oh look, a 🦀! :p

Booleans

The boolean sort in Rust shops solely one among two doable values: both true or false. Should you want to annotate the sort, use bool to point the sort.

fn principal() {
    let val_t: bool = true;
    let val_f = false;

    println!("val_t: {val_t}");
    println!("val_f: {val_f}");
}

The above code, when compiled and executed ends in the next output:

val_t: true
val_f: false

Bonus: Specific typecasting

Within the earlier article about Variables within the Rust programming language, I confirmed a really fundamental temperature conversion program. In there, I discussed that Rust doesn’t permit implicit typecasting.

However that does not imply that Rust doesn’t permit express typecasting both 😉

To carry out express sort casting, the as key phrase is used and adopted by the info sort to which the worth needs to be forged in.

Following is a demo program:

fn principal() {
    let a = 3 as f64; // f64
    let b = 3.14159265359 as i32; // i32

    println!("a: {a}");
    println!("b: {b}");
}

On line 2, as an alternative of utilizing ‘3.0’, I comply with the ‘3’ with as f64 to indicate that I need the compiler to deal with sort casting of ‘3’ (an Integer) right into a 64-bit float. Similar with the threerd line. However right here, the sort casting is lossy. That means, that the fractional component is fully gone. As an alternative of storing 3.14159265359, it’s saved as merely 3.

This may be verified from this system’s output:

a: 3
b: 3

Conclusion

This text covers the Primitive/Scalar knowledge sorts in Rust. There are primarily 4 such knowledge sorts: Integers, Floating level numbers, Characters and Booleans.

Integers are used to retailer entire numbers and so they have a number of sub-types based mostly on both they’re signed or unsigned and the size. Floating level numbers are used to retailer numbers with some fractional values and have two sub-types based mostly on size. The character knowledge sort is used to retailer a single, legitimate UTF-8 encoded character. Lastly, booleans are used to retailer both a true or false worth.

Within the subsequent chapter, I will talk about compound knowledge sorts like arrays and tuples. Keep tuned.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments