Rust

[Rust] Data Type

llHoYall 2022. 7. 30. 17:19

Rust is a statically typed language, meaning it must know all variables' types at compile time.

Every value in Rust is of a particular data type.

Rust's data types can be roughly divided into two types, which are scalar and compound.

If we omit explicit data types, the compiler infers it.

Scalar Type

A scalar type represents a single value.

Integer Type

There are signed integers and unsigned integers.

  • Signed: i8, i16, i32, i64, i128, isize
  • Unsigned: u8, u16, u32, u64, u128, usize

The number means the number of bits.

The size means which depends on the architecture of the computer.

 

A number is represented by number literal.

Number literal can have _(underscore) only for readability.

  • Binary: 0b1010_0101
  • Octal: 0o153
  • Decimal: 123_456
  • Hex: 0xa6
  • Byte (u8): b‘A’

Floating-Point Type

Floating-point numbers are represented according to the IEEE-754 standard.

  • Floating-point: f32, f64

The f32 type is a single-precision float, and the f64 has double precision.

Boolean Type

Boolean type is represented by bool and can have true and false values.

Character Type

Character type is represented by char.

It is specified with single quotes, as opposed to string literals, which use double quotes.

It is 4 bytes in size and represents a Unicode scalar value.

Example

fn main() {
    let a: u8 = 7;
    // let a = 7u8;
    // let a = 7_u8;
    let b: f64 = 3.14;
    let c: bool = true;
    let d: char = 'a';
}

Compound Type

Compound types can group multiple values into one type.

Tuple Type

A tuple groups together a number of values with a variety of types into one compound type.

The tuple has a fixed length that does not change once it is declared.

A tuple is created by writing a comma-separated list of values inside parentheses.

Rust supports destructuring in the tuple.

We can access elements inside a tuple by using a .(dot) followed by the index of the value we want to access.

fn main() {
    // Creating
    let tuple: (u8, i32, f64) = (32, -7, 3.14);
    
    // Destructuring
    let (x, y, z) = tuple;
    
    // Accessing
    let a = tuple.1; // -7
}

Array Type

Unlike a tuple, every element of an array must have the same type.

The array also has a fixed length like a tuple.

An array is created by writing a comma-separated list of values inside square brackets.

fn main() {
    // Creating
    let nums1:[u8; 3] = [1, 2, 3];
    let nums2 = [1; 3]; // [1, 1, 1]
    
    // Accessing
    let x = nums1[1]; // 2
    let y = nums2[2]; // 1
}

Type Conversion

Types can be converted using as keyword.

fn main() {
    let a: i32 = 37;
    let b: u16 = 65;

    if a < (b as i32) {
        println!("a is lesser than b");
    }
}

Rust cannot compare to different type, so converted type using as in this example.