Skip to main content


Day 7: Rust hate Implicit

Welcome back fellow Rustaceans 🦀!!

In the last article, we took a look at the nitty-gritty details of variables in Rust. We missed one more detail, the type conversion!! Today, we're going to have a look at type conversions in Rust and how they differ from C.

Rust and C have quite different philosophies when it comes to how they handle type conversions. C is quite permissive, often performing conversions between numeric types automatically, even if it might lead to unexpected results. Rust, on the other hand, prioritizes safety and predictability, requiring developers to be explicit about type conversions.

Let's take a look at a simple C example:

#include <stdio.h>

int main() {
    double pi = 3.14;
    int whole_pi = pi;  // Implicit conversion from double to int
    printf("Whole part of pi: %d\n", whole_pi);  // Output: 3

In this code, we assign a double value (3.14) to an int variable (whole_pi). C happily performs the conversion, silently truncating (cutting off) the decimal part. This implicit conversion might seem convenient, but it can hide potential issues. What if the loss of precision matters in later calculations?

Let's see what happens when we try the same type of code in Rust.

fn main() {
    let pi:f64 = 3.14;     // Rust infers the type as f64 (double)
    let whole_pi:u32 = pi; // Error! Type mismatch (f64 to i32) 
    println!("Whole part of pi: {}", whole_pi);