Data types in Rust

codernineteen·2022년 1월 14일

Rust dev

목록 보기

Data types

Every values in rust have a certain date type.
For example, when we convert string type to number type , we must add type annotation(: type) next to variable
let guess: u32 = "42".parse().expect("Not a number!");

Scalar types

Four types: intergers, floating-point, numbers, Booleans, and characters.

  • interger : is a number without a fractional component.
    - There is i8/16/32/64/128/size and u8/16/32/64/128/size. Each number points its size of interger. For example, u8 is unsigned interger which has 8 bits size. Unsigned interger(starts with 'u') can be negative nubmer. You can think of '-' sign if you don't get it concept of signed or unsigned.
    - Signed variants can store numbers from 2^(n - 1) to 2^(n - 1) - 1. For example, i8 can include 2^7 ~ 2^7 -1(128 ~ 127).
    - Signed variants can store numbers from 0 to 2^n - 1. For example, u8 can include 0 ~ 2^8 - 1(0 ~ 255).
    - isize , usize depends on architecture of your computer program

  • floating-point : is a number with decimal points.
    There are f32 and f64 types.
    - Rusts supports basic numeric operations(addition, subtraction, multiplication, division, and remainder). Interger division rounds down to the nearest interger.

  • boolean : Type name is 'bool'.true or false.

  • character : Type name is 'char'. char type is four bytes size and represents Unicode (it can represent a lot more than ASCII)
    Accented letters; Chinese, Japanese, and Korean characters; emoji; and zero-width spaces are all valid char values in Rust.

Compound types

  • tuple : Tuples have fixed length, and once they declared, they can't expand or shrink. There is no type limitation of items
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);

You can destructure tuple like this.

fn main() {
    let tup = (500, 6.4, 1);

    let (x, y, z) = tup;

    println!("The value of y is: {}", y);

You can access tuple by using index

fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);

    let five_hundred = x.0;

    let six_point_four = x.1;

    let one = x.2;
  • array : Array type has element type limitation. Elements should be same type. In Rust, Array has limited length.
    You write array types using square brackets.
    In Below example, elements type is i32 and number of element is five.
    let a: [i32; 5] = [1, 2, 3, 4, 5];
    Indexing is same with other languages.
슈퍼 주니어 개발자

0개의 댓글