mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 22:01:18 -06:00
293 lines
17 KiB
HTML
293 lines
17 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Casting between types - </title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body class="light">
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong>1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong>2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong>3.</strong> Syntax and Semantics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> if</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong>3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong>3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong>3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong>3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong>3.12.</strong> Structs</a></li><li><a href="enums.html"><strong>3.13.</strong> Enums</a></li><li><a href="match.html"><strong>3.14.</strong> Match</a></li><li><a href="patterns.html"><strong>3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong>3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong>3.17.</strong> Strings</a></li><li><a href="generics.html"><strong>3.18.</strong> Generics</a></li><li><a href="traits.html"><strong>3.19.</strong> Traits</a></li><li><a href="drop.html"><strong>3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong>3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong>3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong>3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong>3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong>3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong>3.26.</strong> <code>const</code> and <code>static</code></a></li><li><a href="attributes.html"><strong>3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong>3.28.</strong> <code>type</code> aliases</a></li><li><a href="casting-between-types.html" class="active"><strong>3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong>3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong>3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong>3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong>3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong>3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong>3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong>3.36.</strong> <code>unsafe</code></a></li></ul></li><li><a href="effective-rust.html"><strong>4.</strong> Effective Rust</a></li><li><ul class="section"><li><a href="the-stack-and-the-heap.html"><strong>4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong>4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong>4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong>4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong>4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong>4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong>4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong>4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong>4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong>4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong>4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong>4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong>4.13.</strong> Procedural Macros (and custom derive)</a></li></ul></li><li><a href="glossary.html"><strong>5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong>6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong>7.</strong> Bibliography</a></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar" class="menu-bar">
|
||
<div class="left-buttons">
|
||
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
||
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
||
</div>
|
||
|
||
<h1 class="menu-title"></h1>
|
||
|
||
<div class="right-buttons">
|
||
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="content" class="content">
|
||
<a class="header" href="casting-between-types.html#casting-between-types" name="casting-between-types"><h1>Casting Between Types</h1></a>
|
||
<p>Rust, with its focus on safety, provides two different ways of casting
|
||
different types between each other. The first, <code>as</code>, is for safe casts.
|
||
In contrast, <code>transmute</code> allows for arbitrary casting, and is one of the
|
||
most dangerous features of Rust!</p>
|
||
<a class="header" href="casting-between-types.html#coercion" name="coercion"><h1>Coercion</h1></a>
|
||
<p>Coercion between types is implicit and has no syntax of its own, but can
|
||
be spelled out with <a href="casting-between-types.html#explicit-coercions"><code>as</code></a>.</p>
|
||
<p>Coercion occurs in <code>let</code>, <code>const</code>, and <code>static</code> statements; in
|
||
function call arguments; in field values in struct initialization; and in a
|
||
function result.</p>
|
||
<p>The most common case of coercion is removing mutability from a reference:</p>
|
||
<ul>
|
||
<li><code>&mut T</code> to <code>&T</code></li>
|
||
</ul>
|
||
<p>An analogous conversion is to remove mutability from a
|
||
<a href="raw-pointers.html">raw pointer</a>:</p>
|
||
<ul>
|
||
<li><code>*mut T</code> to <code>*const T</code></li>
|
||
</ul>
|
||
<p>References can also be coerced to raw pointers:</p>
|
||
<ul>
|
||
<li>
|
||
<p><code>&T</code> to <code>*const T</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>&mut T</code> to <code>*mut T</code></p>
|
||
</li>
|
||
</ul>
|
||
<p>Custom coercions may be defined using <a href="deref-coercions.html"><code>Deref</code></a>.</p>
|
||
<p>Coercion is transitive.</p>
|
||
<a class="header" href="casting-between-types.html#as" name="as"><h1><code>as</code></h1></a>
|
||
<p>The <code>as</code> keyword does safe casting:</p>
|
||
<pre><code class="language-rust">let x: i32 = 5;
|
||
|
||
let y = x as i64;
|
||
</code></pre>
|
||
<p>There are three major categories of safe cast: explicit coercions, casts
|
||
between numeric types, and pointer casts.</p>
|
||
<p>Casting is not transitive: even if <code>e as U1 as U2</code> is a valid
|
||
expression, <code>e as U2</code> is not necessarily so (in fact it will only be valid if
|
||
<code>U1</code> coerces to <code>U2</code>).</p>
|
||
<a class="header" href="casting-between-types.html#explicit-coercions" name="explicit-coercions"><h2>Explicit coercions</h2></a>
|
||
<p>A cast <code>e as U</code> is valid if <code>e</code> has type <code>T</code> and <code>T</code> <em>coerces</em> to <code>U</code>.</p>
|
||
<a class="header" href="casting-between-types.html#numeric-casts" name="numeric-casts"><h2>Numeric casts</h2></a>
|
||
<p>A cast <code>e as U</code> is also valid in any of the following cases:</p>
|
||
<ul>
|
||
<li><code>e</code> has type <code>T</code> and <code>T</code> and <code>U</code> are any numeric types; <em>numeric-cast</em></li>
|
||
<li><code>e</code> is a C-like enum (with no data attached to the variants),
|
||
and <code>U</code> is an integer type; <em>enum-cast</em></li>
|
||
<li><code>e</code> has type <code>bool</code> or <code>char</code> and <code>U</code> is an integer type; <em>prim-int-cast</em></li>
|
||
<li><code>e</code> has type <code>u8</code> and <code>U</code> is <code>char</code>; <em>u8-char-cast</em></li>
|
||
</ul>
|
||
<p>For example</p>
|
||
<pre><code class="language-rust">let one = true as u8;
|
||
let at_sign = 64 as char;
|
||
let two_hundred = -56i8 as u8;
|
||
</code></pre>
|
||
<p>The semantics of numeric casts are:</p>
|
||
<ul>
|
||
<li>Casting between two integers of the same size (e.g. i32 -> u32) is a no-op</li>
|
||
<li>Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will
|
||
truncate</li>
|
||
<li>Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will
|
||
<ul>
|
||
<li>zero-extend if the source is unsigned</li>
|
||
<li>sign-extend if the source is signed</li>
|
||
</ul>
|
||
</li>
|
||
<li>Casting from a float to an integer will round the float towards zero
|
||
<ul>
|
||
<li><strong><a href="https://github.com/rust-lang/rust/issues/10184">NOTE: currently this will cause Undefined Behavior if the rounded
|
||
value cannot be represented by the target integer type</a></strong>.
|
||
This includes Inf and NaN. This is a bug and will be fixed.</li>
|
||
</ul>
|
||
</li>
|
||
<li>Casting from an integer to float will produce the floating point
|
||
representation of the integer, rounded if necessary (rounding strategy
|
||
unspecified)</li>
|
||
<li>Casting from an f32 to an f64 is perfect and lossless</li>
|
||
<li>Casting from an f64 to an f32 will produce the closest possible value
|
||
(rounding strategy unspecified)
|
||
<ul>
|
||
<li><strong><a href="https://github.com/rust-lang/rust/issues/15536">NOTE: currently this will cause Undefined Behavior if the value
|
||
is finite but larger or smaller than the largest or smallest finite
|
||
value representable by f32</a></strong>. This is a bug and will
|
||
be fixed.</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
<a class="header" href="casting-between-types.html#pointer-casts" name="pointer-casts"><h2>Pointer casts</h2></a>
|
||
<p>Perhaps surprisingly, it is safe to cast <a href="raw-pointers.html">raw pointers</a> to and
|
||
from integers, and to cast between pointers to different types subject to
|
||
some constraints. It is only unsafe to dereference the pointer:</p>
|
||
<pre><code class="language-rust">let a = 300 as *const char; // `a` is a pointer to location 300.
|
||
let b = a as u32;
|
||
</code></pre>
|
||
<p><code>e as U</code> is a valid pointer cast in any of the following cases:</p>
|
||
<ul>
|
||
<li>
|
||
<p><code>e</code> has type <code>*T</code>, <code>U</code> has type <code>*U_0</code>, and either <code>U_0: Sized</code> or
|
||
<code>unsize_kind(T) == unsize_kind(U_0)</code>; a <em>ptr-ptr-cast</em></p>
|
||
</li>
|
||
<li>
|
||
<p><code>e</code> has type <code>*T</code> and <code>U</code> is a numeric type, while <code>T: Sized</code>; <em>ptr-addr-cast</em></p>
|
||
</li>
|
||
<li>
|
||
<p><code>e</code> is an integer and <code>U</code> is <code>*U_0</code>, while <code>U_0: Sized</code>; <em>addr-ptr-cast</em></p>
|
||
</li>
|
||
<li>
|
||
<p><code>e</code> has type <code>&[T; n]</code> and <code>U</code> is <code>*const T</code>; <em>array-ptr-cast</em></p>
|
||
</li>
|
||
<li>
|
||
<p><code>e</code> is a function pointer type and <code>U</code> has type <code>*T</code>,
|
||
while <code>T: Sized</code>; <em>fptr-ptr-cast</em></p>
|
||
</li>
|
||
<li>
|
||
<p><code>e</code> is a function pointer type and <code>U</code> is an integer; <em>fptr-addr-cast</em></p>
|
||
</li>
|
||
</ul>
|
||
<a class="header" href="casting-between-types.html#transmute" name="transmute"><h1><code>transmute</code></h1></a>
|
||
<p><code>as</code> only allows safe casting, and will for example reject an attempt to
|
||
cast four bytes into a <code>u32</code>:</p>
|
||
<pre><code class="language-rust ignore">let a = [0u8, 0u8, 0u8, 0u8];
|
||
|
||
let b = a as u32; // Four u8s makes a u32.
|
||
</code></pre>
|
||
<p>This errors with:</p>
|
||
<pre><code class="language-text">error: non-scalar cast: `[u8; 4]` as `u32`
|
||
let b = a as u32; // Four u8s makes a u32.
|
||
^~~~~~~~
|
||
</code></pre>
|
||
<p>This is a ‘non-scalar cast’ because we have multiple values here: the four
|
||
elements of the array. These kinds of casts are very dangerous, because they
|
||
make assumptions about the way that multiple underlying structures are
|
||
implemented. For this, we need something more dangerous.</p>
|
||
<p>The <code>transmute</code> function is very simple, but very scary. It tells Rust to treat
|
||
a value of one type as though it were another type. It does this regardless of
|
||
the typechecking system, and completely trusts you.</p>
|
||
<p>In our previous example, we know that an array of four <code>u8</code>s represents a <code>u32</code>
|
||
properly, and so we want to do the cast. Using <code>transmute</code> instead of <code>as</code>,
|
||
Rust lets us:</p>
|
||
<pre><code class="language-rust">use std::mem;
|
||
|
||
fn main() {
|
||
unsafe {
|
||
let a = [0u8, 1u8, 0u8, 0u8];
|
||
let b = mem::transmute::<[u8; 4], u32>(a);
|
||
println!("{}", b); // 256
|
||
// Or, more concisely:
|
||
let c: u32 = mem::transmute(a);
|
||
println!("{}", c); // 256
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We have to wrap the operation in an <code>unsafe</code> block for this to compile
|
||
successfully. Technically, only the <code>mem::transmute</code> call itself needs to be in
|
||
the block, but it's nice in this case to enclose everything related, so you
|
||
know where to look. In this case, the details about <code>a</code> are also important, and
|
||
so they're in the block. You'll see code in either style, sometimes the context
|
||
is too far away, and wrapping all of the code in <code>unsafe</code> isn't a great idea.</p>
|
||
<p>While <code>transmute</code> does very little checking, it will at least make sure that
|
||
the types are the same size. This errors:</p>
|
||
<pre><code class="language-rust ignore">use std::mem;
|
||
|
||
unsafe {
|
||
let a = [0u8, 0u8, 0u8, 0u8];
|
||
|
||
let b = mem::transmute::<[u8; 4], u64>(a);
|
||
}
|
||
</code></pre>
|
||
<p>with:</p>
|
||
<pre><code class="language-text">error: transmute called with differently sized types: [u8; 4] (32 bits) to u64
|
||
(64 bits)
|
||
</code></pre>
|
||
<p>Other than that, you're on your own!</p>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="type-aliases.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="associated-types.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="type-aliases.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="associated-types.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<!-- Local fallback for Font Awesome -->
|
||
<script>
|
||
if ($(".fa").css("font-family") !== "FontAwesome") {
|
||
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
||
}
|
||
</script>
|
||
|
||
<!-- Livereload script (if served using the cli tool) -->
|
||
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|