Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 4e2dbb669434a7691662cb2f0ad38972 > files > 642

rust-doc-1.28.0-1.mga6.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Casting between types - The Rust Programming Language</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">
        <meta name="theme-color" content="#ffffff" />

        <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 href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="_FontAwesome/css/font-awesome.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        
        <link rel="stylesheet" href="src/theme/first-edition.css">
        

        

    </head>
    <body class="light">
        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = 'light'; }
            document.body.className = theme;
            document.querySelector('html').className = theme + ' js';
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong aria-hidden="true">1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong aria-hidden="true">2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong aria-hidden="true">3.</strong> Syntax and Semantics</a></li><li><ol class="section"><li><a href="variable-bindings.html"><strong aria-hidden="true">3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong aria-hidden="true">3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong aria-hidden="true">3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong aria-hidden="true">3.4.</strong> Comments</a></li><li><a href="if.html"><strong aria-hidden="true">3.5.</strong> if</a></li><li><a href="loops.html"><strong aria-hidden="true">3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong aria-hidden="true">3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong aria-hidden="true">3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong aria-hidden="true">3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong aria-hidden="true">3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong aria-hidden="true">3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong aria-hidden="true">3.12.</strong> Structs</a></li><li><a href="enums.html"><strong aria-hidden="true">3.13.</strong> Enums</a></li><li><a href="match.html"><strong aria-hidden="true">3.14.</strong> Match</a></li><li><a href="patterns.html"><strong aria-hidden="true">3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong aria-hidden="true">3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong aria-hidden="true">3.17.</strong> Strings</a></li><li><a href="generics.html"><strong aria-hidden="true">3.18.</strong> Generics</a></li><li><a href="traits.html"><strong aria-hidden="true">3.19.</strong> Traits</a></li><li><a href="drop.html"><strong aria-hidden="true">3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong aria-hidden="true">3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong aria-hidden="true">3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong aria-hidden="true">3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong aria-hidden="true">3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong aria-hidden="true">3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong aria-hidden="true">3.26.</strong> const and static</a></li><li><a href="attributes.html"><strong aria-hidden="true">3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong aria-hidden="true">3.28.</strong> type aliases</a></li><li><a href="casting-between-types.html" class="active"><strong aria-hidden="true">3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong aria-hidden="true">3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong aria-hidden="true">3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong aria-hidden="true">3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong aria-hidden="true">3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong aria-hidden="true">3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong aria-hidden="true">3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong aria-hidden="true">3.36.</strong> unsafe</a></li></ol></li><li><a href="effective-rust.html"><strong aria-hidden="true">4.</strong> Effective Rust</a></li><li><ol class="section"><li><a href="the-stack-and-the-heap.html"><strong aria-hidden="true">4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong aria-hidden="true">4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong aria-hidden="true">4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong aria-hidden="true">4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong aria-hidden="true">4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong aria-hidden="true">4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong aria-hidden="true">4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong aria-hidden="true">4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong aria-hidden="true">4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong aria-hidden="true">4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong aria-hidden="true">4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong aria-hidden="true">4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">4.13.</strong> Procedural Macros (and custom derive)</a></li></ol></li><li><a href="glossary.html"><strong aria-hidden="true">5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong aria-hidden="true">6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong aria-hidden="true">7.</strong> Bibliography</a></li></ol>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="draft-warning" class="warning">
    <span class="message">You are reading an <strong>outdated</strong> edition of TRPL. For more, go <a href="../index.html">here</a>.</span>
    <button type="button" id="hide-draft-warning" title="Hide draft warning" class="button">
        <i class="fa fa-times"></i>
    </button>
</div>
<!-- Hide / unhide warning before it is displayed -->
<script type="text/javascript">
var warning = localStorage.getItem('trpl-first-edition-draft-warning');

if (warning === 'hidden') {
    Array
    .from(document.querySelectorAll('#page-wrapper'))
    .forEach(function(block) { block.classList.remove('has-warning'); });
    var elem = document.getElementById("draft-warning");
    elem.parentNode.removeChild(elem);
}

document.addEventListener("DOMContentLoaded", function(event) { 
    document.getElementById("hide-draft-warning").addEventListener("click", function(e) {
        var elem = document.getElementById("draft-warning");
        elem.parentNode.removeChild(elem);

        localStorage.setItem('trpl-first-edition-draft-warning', 'hidden');
    });
});
</script>

                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                                <i class="fa fa-paint-brush"></i>
                            </button>
                            <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                                <li role="none"><button role="menuitem" class="theme" id="light">Light <span class="default">(default)</span></button></li>
                                <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                            </ul>
                            
                            <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                                <i class="fa fa-search"></i>
                            </button>
                            
                        </div>

                        <h1 class="menu-title">The Rust Programming Language</h1> 

                        <div class="right-buttons">
                            <a href="print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                        </div>
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <a class="header" href="casting-between-types.html#casting-between-types" id="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" id="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>&amp;mut T</code> to <code>&amp;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>&amp;T</code> to <code>*const T</code></p>
</li>
<li>
<p><code>&amp;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" id="as"><h1><code>as</code></h1></a>
<p>The <code>as</code> keyword does safe casting:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x: i32 = 5;

let y = x as i64;
#}</code></pre></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" id="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" id="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 an enum with no data attached to the variants (a &quot;field-less enumeration&quot;),
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><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let one = true as u8;
let at_sign = 64 as char;
let two_hundred = -56i8 as u8;
#}</code></pre></pre>
<p>The semantics of numeric casts are:</p>
<ul>
<li>Casting between two integers of the same size (e.g. i32 -&gt; u32) is a no-op</li>
<li>Casting from a larger integer to a smaller integer (e.g. u32 -&gt; u8) will
truncate</li>
<li>Casting from a smaller integer to a larger integer (e.g. u8 -&gt; 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" id="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><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let a = 300 as *const char; // `a` is a pointer to location 300.
let b = a as u32;
#}</code></pre></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>&amp;[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" id="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><pre class="playpen"><code class="language-rust">use std::mem;

fn main() {
    unsafe {
        let a = [0u8, 1u8, 0u8, 0u8];
        let b = mem::transmute::&lt;[u8; 4], u32&gt;(a);
        println!(&quot;{}&quot;, b); // 256
        // Or, more concisely:
        let c: u32 = mem::transmute(a);
        println!(&quot;{}&quot;, c); // 256
    }
}
</code></pre></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::&lt;[u8; 4], u64&gt;(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>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="type-aliases.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="associated-types.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a href="type-aliases.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="associated-types.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>

        

        

        

        

        
        <script src="searchindex.js" type="text/javascript" charset="utf-8"></script>
        
        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

    </body>
</html>