mkaz.blog

Working with Rust

Numbers

Rust is a typed language, every variable must specify its type. The common number types are integers i32, i64, u32, u64, f64. The number is the bit size and supports 8, 16, 32, 64, and 128 bit numbers. The letter i for signed integer, u for unsigned integer, and f for float.

Get the max or min value for a type using the .max_value() or .min_value() functions.

Signed Ints

TypeFunctionValue
i8i8::max_value()127
i16i16::max_value()32_767
i32i32::max_value()2_147_483_647
i64i64::max_value()9_223_372_036_854_775_807
i128i128::max_value()170141183460469231731687303715884105727

Unsigned Ints

TypeFunctionValue
u8u8::max_value()255
u16u16::max_value()65_535
u32u32::max_value()4_294_967_295
u64u64::max_value()18_446_744_073_709_551_615
u128u128::max_value()340282366920938463463374607431768211455

Basic Math

fn main() {
    let x = 3;
    let y = 6;
    println!("{} + {}: {}", x, y, x + y);
    println!("{} * {}: {}", x, y, x * y);
}

Conversions

String to Integer

To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type it is converting to, this can be specified on the left-side of assignment like so:

let str = "123";
let num: i32 = str.parse().unwrap();

Or can also specify the int type inline, using ::<> syntax:

let str = "123";
let num = str.parse::<i32>().unwrap();

Note: The use of .unwrap() is to "catch" the potential error and fail at this point. This can be used if the string is guarenteed to be a number. If the string is invalid it will fail with a runtime ParseIntError. To code for a potential error match on the Result which returns an Ok or Err:

let str = "a123";
let num = match str.parse::<i32>() {
    Ok(x) => x,
    Err(error) => {
        println!("Error converting number: {}", error);
        println!("Setting num to default: 0");
        0
    }
};
println!("{}", num)

String to a Float

To convert a string to a float in Rust, use the parse() function specifing f32 or f64 for the type. Either specify the float type to the variable you are assigning:

let str = "3.14159";
let pi: f64 = str.parse().unwrap()

Or when converting string to float, specify the float type inline to the parse function, using ::<> syntax:

let str = "2.71828";
let e = str.parse::<f32>().unwrap();

Char to a Integer

To convert a single char to an integer in Rust, use .to_digit(RADIX). The radix value is used for conversion, 10 for decimal, 16 for hexadecimal.

let ch = '2';
let num = ch.to_digit(10).unwrap();
let ch = 'f';
let num = ch.to_digit(16).unwrap();
println!("{}", num);
// 15

Integer to String

To convert an integer to a string in Rust, use .to_string()

let num = 123;
let str = num.to_string();

Integer to Float

To convert an integer to a float in Rust, use as f64. This is a useful means to convert from various interchangeable types, you can use inline also.

let num = 13;
let flt = num as f64;
println!("{}", 1.2 * flt);
println!("{}", 1.2 * num as f64);

Float to Integer

Use the same as to cast a float to an integer type. By default, it will discard the decimal portion of the number giving you an equivalent of floor(). Use .round() or .ceil() prior to control how you want the float to be converted.

let num = 13.6 as f32;
let i = num as i32;
let j = num.round() as i32;
let k = num.ceil() as i32;
println!("{} {} {}", i, j, k);

Convert String from any Number Base

Use from_str_radix() function defined on the different integer types, to specify the string and what base you are converting it from. Here are some examples:

Binary to Integer

To convert a binary string to an integer in Rust:

let bin = "101101";
let i = i32::from_str_radix(bin, 2).unwrap();
println!("{}", i);

Octal to Integer

To convert an octal stirng to an integer in Rust:

let oct = "43127";
let i = i64::from_str_radix(oct, 8).unwrap();
println!("{}", i);

Hexadecimal to Integer

To convert a hexadecimal string to an integer in Rust:

let hex = "5F259A";
let i = u32::from_str_radix(hex, 16).unwrap();
println!("{}", i);

Convert Number to any Number Base String

To convert a number to a string in any number base, use the format!() macro specifing, b for binary, o for octal, x for Hex (or X for HEX). Here are some examples:

Convert Integer to Binary String

To convert an integer to binary in Rust:

let i = 123;
let s = format!("{:b}", i);
println!("{}", s);

Convert Integer to Octal String

To convert an integer to octal in Rust:

let i = 123;
let s = format!("{:o}", i);
println!("{}", s);

Convert Integer to Hexadecimal String

To convert an integer to hexadecimal in Rust:

let i = 123;
let s = format!("{:x}", i); // lowercase
let ss = format!("{:X}", i); // uppercase
println!("{}, {}", s, ss);

Generate Random Number

To generate a random number in Rust use the rand crate.

First, add the following to Cargo.toml

[dependencies]
rand = "0.8.5"

In the code, use the .gen_range() function to set the range to pick from. Remember, a Rust range is inclusive of the first number, but exclusive of the second. So 0..100 will pick a number from 0-99.

use rand::Rng;
 
fn main() {
    let num = rand::thread_rng().gen_range(0..100);
    println!("{}", num);
}

See: Example in Rust Playgroud