Mettle

M0119Narrowing conversion needs a cast

Reported by the compiler as an error or warning.

mettle explain M0119

A value flows into a type that cannot hold every value the source type can. Mettle converts silently in one direction only:

Widen silently. Narrow loudly.

So int32 -> int64 and uint32 -> int64 need nothing written, because every value survives them. int64 -> int32, uint64 -> int64 and int32 -> uint32 do, because some values do not.

Example

fn f(n: int64) {
    var small: int32 = n;         // M0119
    var ok:    int32 = (int32)n;  // says the wrap is meant
}

A compile-time constant is exempt: its value is known, so var b: uint8 = 200; is checked rather than refused (see M0118 for the case where it does not fit).

Two destinations sit outside the rule because they are not range conversions: bool is a truth coercion, and an enum names a set. Floating-point conversions are unchanged and still silent.

Related