Rust

E0512 Transmute Size Mismatch Fix

std::mem::transmute reinterprets the bits of a value as another type, and a bit-for-bit reinterpretation only makes sense when there are exactly as many bits on both sides. E0512 is the compiler checking that arithmetic before the unsafe block ever runs: the source type and the target type have different sizes, or one of them has no fixed size at all. This guide separates the eleven shapes that produce it - widening, narrowing, scalar against scalar, reference against fat reference, array, tuple, and struct against a wider type, a value against a reference, and a generic pair with no known size - and matches each one to its repair: make the sizes equal, or use the named conversion that does the widening, narrowing, padding, or checking transmute was being asked to fake.

Written November 25, 2026 · Tested with Rust 1.99.1 · 32 min read

By the end of this guide
  • The rule underneath: same size, guaranteed
  • How to read the diagnostic
  • The first failure: a smaller integer to a larger one
  • The second failure: a larger integer to a smaller one

Written November 25, 2026

Tested with Rust 1.99.1

What this guide is

Error E0512 is a transmute between types of different sizes. The error codes index defines it in one line - transmute with two differently sized types was attempted - and its example is a u16 transmuted where a u8 is expected. The documentation for std::mem::transmute states the rule the error enforces: both types must have the same size, and compilation will fail if this is not guaranteed. The diagnostic carries the whole diagnosis in its two notes - "source type: u8 (8 bits)" and "target type: u16 (16 bits)" - so the first step with any E0512 is to read those two numbers: they say which direction the mismatch runs and by how much.

The forms in this guide each reproduce E0512 with a small, complete program, and each pairs the two types differently: a smaller integer against a larger one and the reverse, a bool and a char against integers of other widths, a thin reference against a fat slice reference, a two-byte array, a two-field tuple, and a one-field struct against wider targets, the error index's own argument-position example, a value against a reference, and a generic pair whose sizes are not known at all. The fixes split into two kinds. Where a genuine bit reinterpretation between equal-size types is what the code means, the fix keeps transmute and changes one side until the sizes match. Everywhere else, the fix drops transmute for the conversion that names the actual intent - widening with from, narrowing with try_from, building an integer from its bytes, or taking a reference directly - because most E0512 failures are not reinterpretations at all: they are ordinary conversions that reached for transmute and were stopped by the size check before they could silently invent or discard bits.

Several neighboring results are not E0512 and are worked only in the traps and the checklist. An equal-size transmute compiles - a bool to a u8, a u32 to its four bytes - though the compiler warns where a named conversion does the same job. An as cast between the same mismatched widths compiles too, because casts are allowed to truncate and extend where transmute is not. transmute_copy compiles across a size mismatch, because it performs no equality check. And a transmute between two references compiles even when the types they point at differ in size, because the references themselves are the same size - the sharpest reminder in the guide that E0512 checks the two named types and nothing behind them.

Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the file names are the bare names shown on the command line.

The rule underneath: same size, guaranteed

The transmute documentation describes the operation as reinterpreting the bits of a value of one type as another type, semantically equivalent to a bitwise move of one type into another. A bitwise move has nothing to do with the extra bits when the target is wider, and nowhere to put the surplus bits when the target is narrower - which is why the same page states the precondition flatly: both types must have the same size, and compilation will fail if this is not guaranteed. The second half of that sentence is the generic family's whole story: a transmute between two type parameters fails not because their sizes are known to differ, but because they are not known to be equal. The error codes index names the two repairs for its example: use types with the same size, or use the expected type directly - its fixed example transmutes an i8 where a u8 is expected, and its alternative passes a plain 0u8 with no transmute at all.

The same documentation is blunt about the standing of the operation itself: transmute is incredibly unsafe, it should be the absolute last resort, and both the argument and the result must be valid at their given types, with undefined behavior as the price of getting that wrong. Size equality is only the one condition the compiler can check for you. It says nothing about validity - not every bit pattern of one type is a legal value of another type of the same size - and nothing about alignment of pointed-to values when pointers or references are transmuted, which the caller has to ensure. The documentation's alternatives section is the practical consequence: turning raw bytes into an integer is from_ne_bytes, from_le_bytes, or from_be_bytes; turning a pointer into an integer is an as cast; turning a &str into bytes is as_bytes. Read E0512 as the compiler steering a conversion toward that list: the sizes differing is usually the sign that the operation was a conversion wearing a reinterpretation's clothes.

Sizes in this guide are stated in bits in the diagnostics and in bytes in the size_of trap, and both are the same measurements: a u8 is 8 bits and 1 byte, a u16 is 16 bits and 2 bytes, a u32 and a char are 32 bits and 4 bytes, a bool is 8 bits and 1 byte, a reference on the platform these programs were built on is 64 bits and 8 bytes, and a slice reference, which carries a length beside the pointer, is 128 bits and 16 bytes. When a diagnostic surprises you - a char wider than expected, a tuple exactly as wide as its fields - the size_of program in the traps is the way to check the pair before choosing a repair.

How to read the diagnostic

Every failure in the eleven families prints the same shape of output. The first family's, in full:

Terminal
$ rustc --edition 2021 fail_u8_u16.rs -o fail_u8_u16
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_u8_u16.rs:3:27
  |
3 |     let y: u16 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `u8` (8 bits)
  = note: target type: `u16` (16 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

Read it in order. The header is fixed text - it does not name the types, because the notes below it do that job. The span underlines the transmute call itself, the whole expression, wherever it sits: in a let binding in most families, in a function argument in the error index's family, and inside a generic function body in the last family. The two notes are the diagnosis. The source note names the type of the value passed in and its size in bits; the target note names the type the result is used as and its size. Compare the two numbers first. Source smaller than target means the code was asking transmute to invent bits - the repair is a widening conversion, or an explicit construction that says where the extra bits come from. Source larger than target means it was asking transmute to discard bits - the repair is a checked narrowing conversion, an as cast where truncation is genuinely intended, or a byte conversion that names an order. Equal numbers never appear in an E0512 diagnostic for concrete types; when the notes read "this type does not have a fixed size" instead of a number, the failure is the guarantee half of the rule, and the repair is to leave generic code for concrete types or for a conversion trait.

That shape is also the fastest way to plan the fix before touching code. The two type names in the notes, not the surrounding program, decide which family below applies - and the families are organized by exactly those pairs, so the notes point at the section.

The first failure: a smaller integer to a larger one

A program that transmutes a u8 into a u16:

Rust
fn main() {
    let x: u8 = 7;
    let y: u16 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_u8_u16.rs -o fail_u8_u16
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_u8_u16.rs:3:27
  |
3 |     let y: u16 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `u8` (8 bits)
  = note: target type: `u16` (16 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

The source is 8 bits and the target is 16, so a bitwise move would have to invent the upper byte - zero-filled, sign-extended, or something else - and transmute does none of those, because choosing between them is the conversion's job, not a reinterpretation's. The shape appears wherever a value read as a small type - a byte from a file, a field from a packet - is wanted in a wider register for arithmetic, and transmute is reached for as if it were a cast.

The fix is the widening conversion, which for unsigned integers is from and always succeeds:

Rust
fn main() {
    let x: u8 = 7;
    let y: u16 = u16::from(x);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_from_widen.rs -o fix_from_widen
$ ./fix_from_widen
7

The output is 7. The value is extended with zero bits, which is what widening an unsigned integer means, and the conversion says so in its name instead of leaving the upper byte to a reinterpretation that cannot supply it.

The second failure: a larger integer to a smaller one

A program that transmutes a u32 into a u16:

Rust
fn main() {
    let x: u32 = 7;
    let y: u16 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_u32_u16.rs -o fail_u32_u16
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_u32_u16.rs:3:27
  |
3 |     let y: u16 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `u32` (32 bits)
  = note: target type: `u16` (16 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

This is the first family run backwards: 32 bits into 16, so a bitwise move would have to discard the upper half of the value. Whether discarding is safe depends on the value, not the type - 7 narrows cleanly and 70000 does not - and a check that depends on the value belongs in a conversion that can fail, not in a reinterpretation that cannot. The shape appears with counters, lengths, and parsed fields that are carried in a wide type and stored or sent in a narrow one.

The fix is the checked narrowing conversion, try_from, which succeeds when the value fits and returns an error when it does not:

Rust
fn main() {
    let x: u32 = 7;
    let y: u16 = u16::try_from(x).unwrap();
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_tryfrom32.rs -o fix_tryfrom32
$ ./fix_tryfrom32
7

The output is 7. The unwrap here stands where real code handles the error case - a value too large for the target is a fact about the input, and try_from is the conversion that reports it instead of truncating silently. Where truncation is genuinely the intent, the as cast in the traps is the tool, and it compiles across exactly this size gap precisely because truncating is what it is defined to do.

The third failure: a bool to a u32

A program that transmutes a bool into a u32:

Rust
fn main() {
    let x: bool = true;
    let y: u32 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_bool_u32.rs -o fail_bool_u32
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_bool_u32.rs:3:27
  |
3 |     let y: u32 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `bool` (8 bits)
  = note: target type: `u32` (32 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

A bool is 8 bits - one byte, holding 0 or 1 - and the target wants 32. The mismatch is the first family's widening shape with a non-integer source, which is why it is worth separating: the repair is not a generic widening but the bool-to-integer conversion, and the equal-size neighbor in the traps, bool to u8, shows the size is the only thing standing in this program's way. The shape appears when a flag is packed into a numeric field - a status word, a protocol value - wider than a byte.

The fix converts the bool to the target width directly:

Rust
fn main() {
    let x: bool = true;
    let y: u32 = u32::from(x);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_bool_u32.rs -o fix_bool_u32
$ ./fix_bool_u32
1

The output is 1. u32::from on a bool gives 1 for true and 0 for false, at the full target width, with no reinterpretation involved.

The fourth failure: a char to a u8

A program that transmutes a char into a u8:

Rust
fn main() {
    let x: char = 'A';
    let y: u8 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_char_u8.rs -o fail_char_u8
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_char_u8.rs:3:26
  |
3 |     let y: u8 = unsafe { std::mem::transmute(x) };
  |                          ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `char` (32 bits)
  = note: target type: `u8` (8 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

The surprise in this family is the source's size: a char is 32 bits, a full Unicode scalar value, not the single byte its name suggests to anyone arriving from C. The narrowing is therefore the second family's shape - 32 bits into 8 - and it is lossy for most characters even before the size check is considered, since only the lowest byte of the code point would survive. The shape appears when text is handled character by character and a character is wanted as a byte value, usually for ASCII-range data.

The fix converts the char to its numeric code point at the width that holds it:

Rust
fn main() {
    let x: char = 'A';
    let y: u32 = x as u32;
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_char_u32.rs -o fix_char_u32
$ ./fix_char_u32
65

The output is 65, the code point of A. A char casts to u32 with as, and that number is the value the program was after; where a single byte is genuinely required, the code point is then narrowed with try_from, which fails for any character above the byte range instead of keeping only its lowest byte.

The fifth failure: a reference to a slice reference

A program that transmutes a reference to a single byte into a slice reference:

Rust
fn main() {
    let x: u8 = 7;
    let r: &u8 = &x;
    let s: &[u8] = unsafe { std::mem::transmute(r) };
    println!("{}", s.len());
}
Terminal
$ rustc --edition 2021 fail_ref_slice.rs -o fail_ref_slice
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_ref_slice.rs:4:29
  |
4 |     let s: &[u8] = unsafe { std::mem::transmute(r) };
  |                             ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `&u8` (64 bits)
  = note: target type: `&[u8]` (128 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

Both sides are references, and they still differ: a reference to one value is a single pointer, 64 bits on this platform, while a slice reference is a pointer plus a length, 128 bits. The missing 64 bits are the length - the one piece of information a slice cannot be used without - and no reinterpretation of the pointer can supply it. The shape appears when a single value needs to be handed to an API that takes a slice, and transmute is reached for to manufacture the slice.

The fix builds the slice with the length stated, using std::slice::from_ref:

Rust
fn main() {
    let x: u8 = 7;
    let s: &[u8] = std::slice::from_ref(&x);
    println!("{}", s.len());
}
Terminal
$ rustc --edition 2021 fix_slice_from_ref.rs -o fix_slice_from_ref
$ ./fix_slice_from_ref
1

The output is 1. The slice has the value's address and a length of one element, both supplied by the constructor instead of half of them being invented by a transmute that the size check stopped.

The sixth failure: a two-byte array to a u32

A program that transmutes a [u8; 2] into a u32:

Rust
fn main() {
    let x: [u8; 2] = [1, 2];
    let y: u32 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_array_u32.rs -o fail_array_u32
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_array_u32.rs:3:27
  |
3 |     let y: u32 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `[u8; 2]` (16 bits)
  = note: target type: `u32` (32 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

An array's size is its element size times its length, so [u8; 2] is 16 bits against the target's 32 - the widening shape again, with the added question of byte order that a wider target would have hidden. The transmute documentation uses exactly this operation, bytes into an integer, as its first alternative: turning raw bytes into a u32 or an f64 is what from_ne_bytes, from_le_bytes, and from_be_bytes are for. The shape appears in parsing code, where a field's bytes are read into an array and wanted as a number.

The fix reads the array as the integer it actually is - a u16, the width the two bytes hold:

Rust
fn main() {
    let x: [u8; 2] = [1, 2];
    let y: u16 = u16::from_ne_bytes(x);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_bytes_u16.rs -o fix_bytes_u16
$ ./fix_bytes_u16
513

The output is 513. On this platform the native byte order places the first byte lowest, so the value is 2 × 256 + 1; from_le_bytes or from_be_bytes pins that order explicitly where the bytes come from a file or a wire rather than from memory. If a u32 is genuinely the target, the input needs four bytes - the array was the wrong size, not the conversion.

The seventh failure: a small struct to a large struct

A program that transmutes a one-field struct into a wider one-field struct:

Rust
struct Small(u8);
struct Large(u32);
fn main() {
    let x = Small(7);
    let y: Large = unsafe { std::mem::transmute(x) };
    println!("{}", y.0);
}
Terminal
$ rustc --edition 2021 fail_struct.rs -o fail_struct
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_struct.rs:5:29
  |
5 |     let y: Large = unsafe { std::mem::transmute(x) };
  |                             ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `Small` (8 bits)
  = note: target type: `Large` (32 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

The notes name the struct types, and their sizes are their fields' sizes: Small is its u8, 8 bits, and Large is its u32, 32 bits. Named types do not change the arithmetic - a struct is exactly as transmutable as the layout it wraps, and here the layouts differ by the same 24 bits as the first family. The shape appears when two versions of a record type - a narrow on-disk form and a wide in-memory form, say - are treated as the same bits instead of as two representations of one value.

The fix converts the field and rebuilds the target struct:

Rust
struct Small(u8);
struct Large(u32);
fn main() {
    let x = Small(7);
    let y = Large(u32::from(x.0));
    println!("{}", y.0);
}
Terminal
$ rustc --edition 2021 fix_struct_wrap.rs -o fix_struct_wrap
$ ./fix_struct_wrap
7

The output is 7. The conversion happens at the field, where the width change actually is, and the struct is constructed normally - the pattern that scales to structs with several fields, each converted on its own terms, where a transmute would have had to match on total size alone and still said nothing about any field's meaning.

The eighth failure: a pair to a u32

A program that transmutes a tuple of two bytes into a u32:

Rust
fn main() {
    let x: (u8, u8) = (1, 2);
    let y: u32 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_tuple.rs -o fail_tuple
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_tuple.rs:3:27
  |
3 |     let y: u32 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `(u8, u8)` (16 bits)
  = note: target type: `u32` (32 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

The size of a tuple is the sum of its fields' sizes here - two bytes, 16 bits - against the target's 32. It is the array family with named positions instead of a uniform element type, and it carries the same hidden question: even at equal total size, which field lands in which byte is a layout decision, not a fact the type of the tuple states. The shape appears when paired values - coordinates, a major and minor version - are packed into one integer for storage or comparison.

The fix states the packing explicitly, building the integer from the bytes in order with the remaining bytes zero:

Rust
fn main() {
    let x: (u8, u8) = (1, 2);
    let y: u32 = u32::from_ne_bytes([x.0, x.1, 0, 0]);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_tuple_bytes.rs -o fix_tuple_bytes
$ ./fix_tuple_bytes
513

The output is 513, the same byte-order result as the array family: the first field lowest, the second next, and the two padding bytes the original program never mentioned now written out in the construction where anyone reading the code can see them.

The ninth failure: the error index's example, in an argument

A program that transmutes a u16 where a function takes a u8 - the error codes index example itself:

Rust
fn takes_u8(_: u8) {}
fn main() {
    unsafe { takes_u8(std::mem::transmute(0u16)); }
}
Terminal
$ rustc --edition 2021 fail_index_u16_u8.rs -o fail_index_u16_u8
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_index_u16_u8.rs:3:23
  |
3 |     unsafe { takes_u8(std::mem::transmute(0u16)); }
  |                       ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `u16` (16 bits)
  = note: target type: `u8` (8 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

Nothing about the position changes the error: the span sits on the transmute call inside the argument, and the target type is inferred from the function's parameter, which is why the program never writes u8 at the call site and the diagnostic still knows it. The notes run 16 bits to 8, the narrowing direction. The index gives this exact program two repairs - use types with the same size, or use the expected type directly.

The fix is the index's same-size repair, transmuting an i8 instead - kept here in the index's own form, warning included, because the warning is part of what this compiler says about it:

Rust
fn takes_u8(_: u8) {}
fn main() {
    unsafe { takes_u8(std::mem::transmute(0i8)); }
    println!("ok");
}
Terminal
$ rustc --edition 2021 trap_equal_i8_u8.rs -o trap_equal_i8_u8
warning: unnecessary transmute
 --> trap_equal_i8_u8.rs:3:23
  |
3 |     unsafe { takes_u8(std::mem::transmute(0i8)); }
  |                       ^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unnecessary_transmutes)]` on by default
help: replace this with
  |
3 -     unsafe { takes_u8(std::mem::transmute(0i8)); }
3 +     unsafe { takes_u8(i8::cast_unsigned(0i8)); }
  |

warning: 1 warning emitted

$ ./trap_equal_i8_u8
ok

The output is ok. The transmute now compiles, because i8 and u8 are both 8 bits - and the compiler immediately suggests cast_unsigned, the named conversion for exactly this pair. The index's second repair is shorter still: pass 0u8 and delete the transmute. Between the two, the second is the one to reach for first; an equal-size transmute that a named conversion covers is a transmute that does not need to exist.

The tenth failure: a value to a reference

A program that transmutes a u8 value into a reference to a u8:

Rust
fn main() {
    let x: u8 = 7;
    let r: &u8 = unsafe { std::mem::transmute(x) };
    println!("{}", r);
}
Terminal
$ rustc --edition 2021 fail_u8_ref.rs -o fail_u8_ref
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_u8_ref.rs:3:27
  |
3 |     let r: &u8 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `u8` (8 bits)
  = note: target type: `&u8` (64 bits)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

An 8-bit value against a 64-bit reference: the size check stops a transmute that would have reinterpreted the byte's bits as a memory address. This is the family where E0512 is doing the most visible protective work - at equal sizes the same idea would compile, and the resulting reference would point at whatever the bits named. The shape appears when a reference is wanted and transmute is treated as a general-purpose converter between any two types that are somehow related - a value and a reference to it being the most common pair.

The fix takes the reference, which was never a conversion at all:

Rust
fn main() {
    let x: u8 = 7;
    let r: &u8 = &x;
    println!("{}", r);
}
Terminal
$ rustc --edition 2021 fix_ref_direct.rs -o fix_ref_direct
$ ./fix_ref_direct
7

The output is 7. Borrowing gives a reference that points at x by construction. The reference family pairs with the fifth: a reference is one pointer wide, a slice reference is two, and any transmute that crosses between values, references, and slices is checked against those widths first - and should be replaced by the borrow or the slice constructor that states the address and the length honestly.

The eleventh failure: a generic pair with no fixed size

A program that transmutes between two type parameters:

Rust
fn swap<T, U>(x: T) -> U {
    unsafe { std::mem::transmute(x) }
}
fn main() {
    let y: u16 = swap(7u8);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fail_generic.rs -o fail_generic
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
 --> fail_generic.rs:2:14
  |
2 |     unsafe { std::mem::transmute(x) }
  |              ^^^^^^^^^^^^^^^^^^^
  |
  = note: source type: `T` (this type does not have a fixed size)
  = note: target type: `U` (this type does not have a fixed size)

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0512`.

The error fires inside the generic function, before any call site is considered, and the notes carry no numbers: neither T nor U has a fixed size the compiler can compare, so the guarantee the transmute documentation requires - compilation fails if same size is not guaranteed - cannot be given. The call in main would mismatch anyway, u8 against u16, but the function is rejected on its own: a generic transmute wrapper is the one shape in this guide that no call site can rescue, because the check happens where the sizes are unknown. The shape appears when transmute is hidden behind a helper written generically to keep call sites short.

The fix leaves the generic wrapper behind and transmutes only at a concrete, equal-size pair:

Rust
fn swap(x: u8) -> i8 {
    unsafe { std::mem::transmute(x) }
}
fn main() {
    let y: i8 = swap(7u8);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_generic_concrete.rs -o fix_generic_concrete
warning: unnecessary transmute
 --> fix_generic_concrete.rs:2:14
  |
2 |     unsafe { std::mem::transmute(x) }
  |              ^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unnecessary_transmutes)]` on by default
help: replace this with
  |
2 -     unsafe { std::mem::transmute(x) }
2 +     unsafe { u8::cast_signed(x) }
  |

warning: 1 warning emitted

$ ./fix_generic_concrete
7

The output is 7. With both types concrete, the compiler can verify 8 bits against 8 bits, and the transmute compiles - with the same warning as the ninth family, pointing at cast_signed. A generic conversion that must stay generic belongs in a trait - From, TryFrom, or a trait of your own - where each implementation is a concrete pair the compiler can check individually.

When the sizes do match: the equal-size transmute

The repair the error index names first - use types with the same size - in its most common form, a u32 reinterpreted as an f32:

Rust
fn main() {
    let x: u32 = 1065353216;
    let y: f32 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_u32_f32.rs -o fix_u32_f32
warning: unnecessary transmute
 --> fix_u32_f32.rs:3:27
  |
3 |     let y: f32 = unsafe { std::mem::transmute(x) };
  |                           ^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unnecessary_transmutes)]` on by default
help: replace this with
  |
3 -     let y: f32 = unsafe { std::mem::transmute(x) };
3 +     let y: f32 = unsafe { f32::from_bits(x) };
  |

warning: 1 warning emitted

$ ./fix_u32_f32
1

The output is 1: the bits 1065353216 are the f32 value 1.0, printed without a fractional part. Both types are 32 bits, so there is no E0512 - and the warning makes the standing point of this guide one more time: even where transmute is legal, a named operation, f32::from_bits, does this exact job. That operation, with no transmute and no warning:

Rust
fn main() {
    let x: u32 = 1065353216;
    let y: f32 = f32::from_bits(x);
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 fix_f32_from_bits.rs -o fix_f32_from_bits
$ ./fix_f32_from_bits
1

The output is 1 again. Keep transmute for the equal-size pairs no named operation covers; the fixes in reach order below start from the conversions, not from the transmute.

The fixes in reach order

  • Read the two notes: source type and size, target type and size. The direction of the gap - source smaller, source larger, or a size not fixed at all - selects the family and the repair before any code changes.
  • The operation is an ordinary conversion wearing a transmute: replace it. Widening is from, narrowing is try_from, a bool is u32::from or u8::from at the width wanted, a char is its code point with as u32 and then a checked narrowing if a byte is required.
  • The source is bytes and the target is a number, or the reverse: use from_ne_bytes, from_le_bytes, or from_be_bytes - and check the array's length against the target's width first, since a length mismatch is this error in array form.
  • One side is a reference or a slice: take the borrow, or build the slice with std::slice::from_ref or a slice expression. Never transmute between a value and a reference, or between a thin and a fat reference.
  • The types are named structs or tuples: convert the fields and rebuild the target. Total-size equality is not field-by-field equivalence, and a field-wise conversion states the packing a transmute would have assumed.
  • A genuine reinterpretation remains, and no named operation covers it: make the two sides exactly the same size - check both with std::mem::size_of if either is a named type - and transmute. Equal size is necessary; validity of every bit pattern at the target type is still your problem.
  • The transmute sits inside a generic function: take it out. Transmute only at concrete types, and put generic conversions behind From or TryFrom implementations.
  • The sizes match and it still will not compile, or it compiles and misbehaves: the defect is no longer E0512's - validity, alignment of pointed-to values, and padding are the remaining transmute hazards, and none of them has a diagnostic as helpful as this one.

Traps

  • Measuring the pair with size_of settles every size claim in this guide. Here the sizes behind the families, in bytes:
Rust
fn main() {
    println!("u8={} u16={} u32={} bool={} char={}", std::mem::size_of::<u8>(), std::mem::size_of::<u16>(), std::mem::size_of::<u32>(), std::mem::size_of::<bool>(), std::mem::size_of::<char>());
    println!("[u8; 2]={} (u8, u8)={} &u8={} &[u8]={}", std::mem::size_of::<[u8; 2]>(), std::mem::size_of::<(u8, u8)>(), std::mem::size_of::<&u8>(), std::mem::size_of::<&[u8]>());
}
Terminal
$ rustc --edition 2021 trap_sizeof.rs -o trap_sizeof
$ ./trap_sizeof
u8=1 u16=2 u32=4 bool=1 char=4
[u8; 2]=2 (u8, u8)=2 &u8=8 &[u8]=16
Trap
The output confirms the diagnostics: char is 4 bytes, not 1; the pair and the array are both 2; and the slice reference is exactly twice the plain reference, the length accounting for the difference. When a named type's size is in doubt, this program - not the type's name, and not its widest field alone - is the check. - A bool to a u8 compiles, because both are one byte. Here the third family's operation at equal size:
Rust
fn main() {
    let x: bool = true;
    let y: u8 = unsafe { std::mem::transmute(x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 trap_bool_u8.rs -o trap_bool_u8
warning: unnecessary transmute
 --> trap_bool_u8.rs:3:26
  |
3 |     let y: u8 = unsafe { std::mem::transmute(x) };
  |                          ^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unnecessary_transmutes)]` on by default
help: replace this with
  |
3 -     let y: u8 = unsafe { std::mem::transmute(x) };
3 +     let y: u8 = unsafe { u8::from(x) };
  |

warning: 1 warning emitted

$ ./trap_bool_u8
1

The output is 1. The third family failed on width alone - bool against u32 - and at the bool's own width the transmute is legal, though the warning again names the conversion, u8::from, that makes the transmute unnecessary. Equal size opens the door; it does not make walking through it the best option. - A u32 to its own four bytes compiles - the array family at equal length. Here a u32 transmuted to [u8; 4]:

Rust
fn main() {
    let x: u32 = 0x12345678;
    let y: [u8; 4] = unsafe { std::mem::transmute(x) };
    println!("{:?}", y);
}
Terminal
$ rustc --edition 2021 trap_u32_bytes.rs -o trap_u32_bytes
warning: unnecessary transmute
 --> trap_u32_bytes.rs:3:31
  |
3 |     let y: [u8; 4] = unsafe { std::mem::transmute(x) };
  |                               ^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: there's also `to_le_bytes` and `to_be_bytes` if you expect a particular byte order
  = note: `#[warn(unnecessary_transmutes)]` on by default
help: replace this with
  |
3 -     let y: [u8; 4] = unsafe { std::mem::transmute(x) };
3 +     let y: [u8; 4] = unsafe { u32::to_ne_bytes(x) };
  |

warning: 1 warning emitted

$ ./trap_u32_bytes
[120, 86, 52, 18]

The output is [120, 86, 52, 18] - the value's bytes lowest first on this platform, which is why the warning offers to_le_bytes and to_be_bytes beside to_ne_bytes: the transmute gives the machine's order, and code that cares which order it gets should say so. Compare the sixth family: same operation, two-byte array, and the only difference is the length that made it E0512. - An as cast across the same gap compiles, because casts are defined to truncate and extend. Here the second family's pair, cast instead of transmuted, with a value that does not fit:

Rust
fn main() {
    let x: u32 = 70000;
    let y: u16 = x as u16;
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 trap_as_truncate.rs -o trap_as_truncate
$ ./trap_as_truncate
4464

The output is 4464 - 70000 with its upper bits discarded, exactly what the cast promises and exactly what try_from in the second family refuses to do silently. E0512 and the cast are the two ends of one choice: transmute guarantees nothing changes size and stops the program when it would; as guarantees the program compiles and changes the value when it must. Pick per call site, on whether truncation is the intent or a hazard. - transmute_copy compiles across a size mismatch, because it performs no size check. Here a u32 copied into a u16:

Rust
fn main() {
    let x: u32 = 7;
    let y: u16 = unsafe { std::mem::transmute_copy(&x) };
    println!("{}", y);
}
Terminal
$ rustc --edition 2021 trap_transmute_copy.rs -o trap_transmute_copy
$ ./trap_transmute_copy
7

The output is 7, read from the first bytes of the u32 on this platform. This is not a repair for any family in this guide: it is the same operation with the one compiler check removed, so the size reasoning E0512 forced - which bytes, in which order, and what happens to the rest - becomes the caller's unverified word. Where a smaller target is read out of a larger value's bytes, the byte conversions state that reasoning in checkable code. - A transmute between two references compiles even when the pointee sizes differ, because the references are the same size. Here a &u8 transmuted to a &u32, measured but never dereferenced:

Rust
fn main() {
    let x: u8 = 7;
    let r: &u8 = &x;
    let s: &u32 = unsafe { std::mem::transmute(r) };
    println!("{}", std::mem::size_of_val(&s));
}
Terminal
$ rustc --edition 2021 trap_ref_pointee.rs -o trap_ref_pointee
$ ./trap_ref_pointee
8

The output is 8 - the size of the reference itself, the only size E0512 ever compared. The pointee types are 1 byte and 4 bytes, and that difference is invisible to the size check, which is why this program measures the result instead of reading through it: size equality between the two named types is the compiler's whole guarantee, and everything behind a pointer - the pointee's size, its alignment, how many bytes are actually there to read - remains the caller's responsibility, exactly as the transmute documentation warns for transmuted pointers and references.

Checklist

  • The two notes read first: source type and bits, target type and bits, and the direction of the gap noted before any repair was chosen.
  • Source smaller than target repaired with a widening conversion or an explicit construction stating where the extra bits come from - never a transmute with padding assumed.
  • Source larger than target repaired with try_from, or with an as cast only where truncation is the documented intent at that call site.
  • Bytes and numbers converted with from_ne_bytes, from_le_bytes, or from_be_bytes and their to_ counterparts, with the array length checked against the target's width.
  • A bool converted with from at the target width, and a char converted through its u32 code point, with any narrowing to a byte checked.
  • Values, references, and slices never transmuted into each other: borrows taken directly, slices built with std::slice::from_ref or a slice expression.
  • Structs and tuples converted field by field and rebuilt, with any packing written out in the construction.
  • A remaining transmute checked for exact size equality on both sides - with size_of for named types - and for validity at the target type, which the size check does not cover.
  • No transmute left inside a generic function, and no transmute_copy used as a way around a size mismatch.
  • The fixed program run, and its output checked against what the program was meant to print.

Sources

  • Rust, Error codes index: E0512 — for the definition of the error as a transmute with two differently sized types, its example of a u16 transmuted where a u8 is expected, and the repairs it names: use types with the same size, or use the expected type directly, with its fixed example transmuting an i8 to a u8.
  • Rust, std::mem::transmute — for transmute as a reinterpretation of a value's bits and a bitwise move, for both types having to be the same size with compilation failing if that is not guaranteed, for the argument and the result both having to be valid at their types, for the caller's responsibility for alignment of pointed-to values when pointers and references are transmuted, and for the named alternatives: from_ne_bytes, from_le_bytes, and from_be_bytes for bytes into integers, as casts for pointers into integers, and as_bytes for a string into bytes.

Keep Exploring