Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
This story was originally published on Medium
Follow me:
Introduction
Rust has two data type subsets, scalar, and compound. The scalar types are integers, floating numbers, Booleans, and characters. The compound types are arrays and tuples.
In this article we are going to see why the following code fails:
// When we operate different data types, it fails:
fn main() {
let a: i16 = 2;
let b: u16 = 4;
println!("{}", a+b);
}
And why casting 128
to i8
is -128
.
1
2
3
4
5
#[allow(overflowing_literals)]
fn main() {
println!("128 as a i8 is : {}", 128 as i8);
}
Enter to Rename, Shift+Enter to Preview
To understand better about the casting, we need to review about Signed, Ones’ Complement and Two’s Complement.
We will also cover adding a negative number, bitwise negation, and converting a binary to an unsigned and signed decimal.
Let’s start from Rust integer types first.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content