logo

Programming Languages - Type Casting and Type Conversions

Type Casting vs Type Conversion

  • type conversion / type coercion: implicit, made automatically by compiler.
  • type casting: explicit, done by the programmer using a cast operator.

By Language

C++

Read more: C++ Type Casting

Go

NO implicit conversion in Go: Unlike in C, in Go assignment between items of different type requires an explicit conversion. (Otherwise build would fail.)

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

i := 42
f := float64(i)
u := uint(f)

Use strconv in the standard library to convert between strings and numbers: https://pkg.go.dev/strconv

Rust

Explicit type conversion (casting) can be performed using the as keyword.

let integer = decimal as u8;

Saturating cast: when casting from float to int. If the floating point value exceeds the upper bound or is less than the lower bound, the returned value will be equal to the bound crossed.

// result is 255
300.0_f32 as u8

// result is 0
-100.0_f32 as u8

// result is 0
f32::NAN as u8

Use unsafe to bypass this, but may overflow:

unsafe {
    // result is 44
    300.0_f32.to_int_unchecked::<u8>()

    // result is 156
    (-100.0_f32).to_int_unchecked::<u8>()
}

Java

Order of the types:

  • byte -> short -> int -> long -> float -> double

Supports implicit "widening" conversion:

int a = 1;
long b = 2L;
b = a; // OK, now b == 1

A "narrowing" conversion needs an explicit cast:

int a = 1;
long b = 2L;
a = b; // Error: incompatible types: possible lossy conversion from long to int
a = (int)b; // OK

Cast to another class:

(AnotherClass) object;

Between Strings and numerics:

// Integer to String
String s = Integer.toString(i);
String s = String.valueOf(i);

// String to int
int i = Integer.parseInt(s)

Read more: Java Cheatsheet

JavaScript

Implicit conversion:

let str = 'The number is: ' + num;

Explicit conversion:

parseInt(str);
parseFloat(str);

const num = Number(str);

Cast objects: use Object.assign(). The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object.