Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 564935689ab5527f955e5449ded02799 > files > 306

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

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Unsafe Rust - 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">

        <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">
        <style>
            .page-wrapper.has-warning > .nav-chapters {
              /* add height for warning content & margin */
              top: 120px;
            }

            p.warning {
                background-color: rgb(242, 222, 222);
                border-bottom-color: rgb(238, 211, 215);
                border-bottom-left-radius: 4px;
                border-bottom-right-radius: 4px;
                border-bottom-style: solid;
                border-bottom-width: 0.666667px;
                border-image-outset: 0 0 0 0;
                border-image-repeat: stretch stretch;
                border-image-slice: 100% 100% 100% 100%;
                border-image-source: none;
                border-image-width: 1 1 1 1;
                border-left-color: rgb(238, 211, 215);
                border-left-style: solid;
                border-left-width: 0.666667px;
                border-right-color: rgb(238, 211, 215);
                border-right-style: solid;
                border-right-width: 0.666667px;
                border-top-color: rgb(238, 211, 215);
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                border-top-style: solid;
                border-top-width: 0.666667px;
                color: rgb(185, 74, 72);
                margin-bottom: 0px;
                margin-left: 0px;
                margin-right: 0px;
                margin-top: 30px;
                padding-bottom: 8px;
                padding-left: 14px;
                padding-right: 35px;
                padding-top: 8px;
            }
            p.warning strong {
                color: rgb(185, 74, 72)
            }
            p.warning a {
                color: rgb(0, 136, 204)
            }
        </style>

        <!-- 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><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Using Structs to Structure Related Data</a></li><li><ul class="section"><li><a href="ch05-01-defining-structs.html"><strong>5.1.</strong> Defining and Instantiating Structs</a></li><li><a href="ch05-02-example-structs.html"><strong>5.2.</strong> An Example Program Using Structs</a></li><li><a href="ch05-03-method-syntax.html"><strong>5.3.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> Common Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Validating References with Lifetimes</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="ch15-01-box.html"><strong>15.1.</strong> <code>Box&lt;T&gt;</code> Points to Data on the Heap and Has a Known Size</a></li><li><a href="ch15-02-deref.html"><strong>15.2.</strong> The <code>Deref</code> Trait Allows Access to the Data Through a Reference</a></li><li><a href="ch15-03-drop.html"><strong>15.3.</strong> The <code>Drop</code> Trait Runs Code on Cleanup</a></li><li><a href="ch15-04-rc.html"><strong>15.4.</strong> <code>Rc&lt;T&gt;</code>, the Reference Counted Smart Pointer</a></li><li><a href="ch15-05-interior-mutability.html"><strong>15.5.</strong> <code>RefCell&lt;T&gt;</code> and the Interior Mutability Pattern</a></li><li><a href="ch15-06-reference-cycles.html"><strong>15.6.</strong> Creating Reference Cycles and Leaking Memory is Safe</a></li></ul></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Fearless Concurrency</a></li><li><ul class="section"><li><a href="ch16-01-threads.html"><strong>16.1.</strong> Threads</a></li><li><a href="ch16-02-message-passing.html"><strong>16.2.</strong> Message Passing</a></li><li><a href="ch16-03-shared-state.html"><strong>16.3.</strong> Shared State</a></li><li><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong>16.4.</strong> Extensible Concurrency: <code>Sync</code> and <code>Send</code></a></li></ul></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust an Object-Oriented Programming Language?</a></li><li><ul class="section"><li><a href="ch17-01-what-is-oo.html"><strong>17.1.</strong> What Does Object-Oriented Mean?</a></li><li><a href="ch17-02-trait-objects.html"><strong>17.2.</strong> Trait Objects for Using Values of Different Types</a></li><li><a href="ch17-03-oo-design-patterns.html"><strong>17.3.</strong> Object-Oriented Design Pattern Implementations</a></li></ul></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns Match the Structure of Values</a></li><li><ul class="section"><li><a href="ch18-01-all-the-places-for-patterns.html"><strong>18.1.</strong> All the Places Patterns May be Used</a></li><li><a href="ch18-02-refutability.html"><strong>18.2.</strong> Refutability: Whether a Pattern Might Fail to Match</a></li><li><a href="ch18-03-pattern-syntax.html"><strong>18.3.</strong> All the Pattern Syntax</a></li></ul></li><li><a href="ch19-00-advanced-features.html"><strong>19.</strong> Advanced Features</a></li><li><ul class="section"><li><a href="ch19-01-unsafe-rust.html" class="active"><strong>19.1.</strong> Unsafe Rust</a></li><li><a href="ch19-02-advanced-lifetimes.html"><strong>19.2.</strong> Advanced Lifetimes</a></li><li><a href="ch19-03-advanced-traits.html"><strong>19.3.</strong> Advanced Traits</a></li><li><a href="ch19-04-advanced-types.html"><strong>19.4.</strong> Advanced Types</a></li><li><a href="ch19-05-advanced-functions-and-closures.html"><strong>19.5.</strong> Advanced Functions &amp; Closures</a></li></ul></li><li><a href="ch20-00-final-project-a-web-server.html"><strong>20.</strong> Final Project: Building a Multithreaded Web Server</a></li><li><ul class="section"><li><a href="ch20-01-single-threaded.html"><strong>20.1.</strong> A Single Threaded Web Server</a></li><li><a href="ch20-02-slow-requests.html"><strong>20.2.</strong> How Slow Requests Affect Throughput</a></li><li><a href="ch20-03-designing-the-interface.html"><strong>20.3.</strong> Designing the Thread Pool Interface</a></li><li><a href="ch20-04-storing-threads.html"><strong>20.4.</strong> Creating the Thread Pool and Storing Threads</a></li><li><a href="ch20-05-sending-requests-via-channels.html"><strong>20.5.</strong> Sending Requests to Threads Via Channels</a></li><li><a href="ch20-06-graceful-shutdown-and-cleanup.html"><strong>20.6.</strong> Graceful Shutdown and Cleanup</a></li></ul></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> A - Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> B - Operators</a></li><li><strong>21.3.</strong> C - Derivable Traits</li><li><strong>21.4.</strong> D - Nightly Rust</li><li><strong>21.5.</strong> E - Macros</li><li><strong>21.6.</strong> F - Translations</li><li><a href="appendix-07-newest-features.html"><strong>21.7.</strong> G - Newest Features</a></li></ul></li></ul>
        </div>

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

            <div class="page">
                <header><p class="warning">You are reading a <strong>draft</strong> of the next edition of TRPL. For more, go <a href="../index.html">here</a>.</p></header>
                <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">The Rust Programming Language</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="ch19-01-unsafe-rust.html#unsafe-rust" id="unsafe-rust"><h2>Unsafe Rust</h2></a>
<p>In all of the previous chapters in this book, we've been discussing code
written in Rust that has memory safety guarantees enforced at compile time.
However, Rust has a second language hiding out inside of it, unsafe Rust, which
does not enforce these memory safety guarantees. Unsafe Rust works just like
regular Rust does, but it gives you extra superpowers not available in safe
Rust code.</p>
<p>Unsafe Rust exists because, by nature, static analysis is conservative. When
trying to determine if code upholds some guarantees or not, it's better to
reject some programs that are valid than it is to accept some programs that are
invalid. There are some times when your code might be okay, but Rust thinks
it's not! In these cases, you can use unsafe code to tell the compiler, &quot;trust
me, I know what I'm doing.&quot; The downside is that you're on your own; if you get
unsafe code wrong, problems due to memory unsafety like null pointer
dereferencing can occur.</p>
<p>There's another reason that Rust needs to have unsafe code: the underlying
hardware of computers is inherently not safe. If Rust didn't let you do unsafe
operations, there would be some tasks that you simply could not do. But Rust
needs to be able to let you do low-level systems programming like directly
interacting with your operating system, or even writing your own operating
system! That's part of the goals of the language. We need some way to do these
kinds of things.</p>
<a class="header" href="ch19-01-unsafe-rust.html#unsafe-superpowers" id="unsafe-superpowers"><h3>Unsafe Superpowers</h3></a>
<p>We switch into unsafe Rust by using the <code>unsafe</code> keyword and starting a new
block that holds the unsafe code. There are four actions that you can take in
unsafe Rust that you can't in safe Rust. We call these the &quot;unsafe
superpowers.&quot; We haven't seen most of these features yet since they're only
usable with <code>unsafe</code>!</p>
<ol>
<li>Dereferencing a raw pointer</li>
<li>Calling an unsafe function or method</li>
<li>Accessing or modifying a mutable static variable</li>
<li>Implementing an unsafe trait</li>
</ol>
<p>It's important to understand that <code>unsafe</code> doesn't turn off the borrow checker
or disable any other of Rust's safety checks: if you use a reference in unsafe
code, it will still be checked. The only thing the <code>unsafe</code> keyword does is
give you access to these four features that aren't checked by the compiler for
memory safety. You still get some degree of safety inside of an unsafe block!
Furthermore, <code>unsafe</code> does not mean the code inside the block is dangerous or
definitely will have memory safety problems: the intent is that you as the
programmer will ensure that the code inside an <code>unsafe</code> block will have valid
memory, since you've turned off the compiler checks.</p>
<p>People are fallible, however, and mistakes will happen. By requiring these four
unsafe operations to be inside blocks annotated with <code>unsafe</code>, if you make a
mistake and get an error related to memory safety, you'll know that it has to
be related to one of the places that you opted into this unsafety. That makes
the cause of memory safety bugs much easier to find, since we know Rust is
checking all of the other code for us. To get this benefit of only having a few
places to investigate memory safety bugs, it's important to contain your unsafe
code to as small of an area as possible. Any code inside of an <code>unsafe</code> block
is suspect when debugging a memory problem: keep <code>unsafe</code> blocks small and
you'll thank yourself later since you'll have less code to investigate.</p>
<p>In order to isolate unsafe code as much as possible, it's a good idea to
enclose unsafe code within a safe abstraction and provide a safe API, which
we'll be discussing once we get into unsafe functions and methods. Parts of the
standard library are implemented as safe abstractions over unsafe code that has
been audited. This prevents uses of <code>unsafe</code> from leaking out into all the
places that you or your users might want to make use of the functionality
implemented with <code>unsafe</code> code, since using a safe abstraction is safe.</p>
<p>Let's talk about each of the four unsafe superpowers in turn, and along the way
we'll look at some abstractions that provide a safe interface to unsafe code.</p>
<a class="header" href="ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer" id="dereferencing-a-raw-pointer"><h3>Dereferencing a Raw Pointer</h3></a>
<p>Way back in Chapter 4, we first learned about references. We also learned that
the compiler ensures that references are always valid. Unsafe Rust has two new
types similar to references called <em>raw pointers</em>. Just like references, we can
have an immutable raw pointer and a mutable raw pointer. In the context of raw
pointers, &quot;immutable&quot; means that the pointer can't be directly dereferenced and
assigned to. Listing 19-1 shows how to create raw pointers from references:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let mut num = 5;

let r1 = &amp;num as *const i32;
let r2 = &amp;mut num as *mut i32;

#}</code></pre></pre>
<p><span class="caption">Listing 19-1: Creating raw pointers from references</span></p>
<p>The <code>*const T</code> type is an immutable raw pointer, and <code>*mut T</code> is a mutable raw
pointer. We've created raw pointers by using <code>as</code> to cast an immutable and a
mutable reference into their corresponding raw pointer types. Unlike
references, these pointers may or may not be valid.</p>
<p>Listing 19-2 shows how to create a raw pointer to an arbitrary location in
memory. Trying to use arbitrary memory is undefined: there may be data at that
address, there may not be any data at that address, the compiler might optimize
the code so that there is no memory access, or your program might segfault.
There's not usually a good reason to be writing code like this, but it is
possible:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let address = 0x012345;
let r = address as *const i32;

#}</code></pre></pre>
<p><span class="caption">Listing 19-2: Creating a raw pointer to an arbitrary
memory address</span></p>
<p>Note there's no <code>unsafe</code> block in either Listing 19-1 or 19-2. You can <em>create</em>
raw pointers in safe code, but you can't <em>dereference</em> raw pointers and read
the data being pointed to. Using the dereference operator, <code>*</code>, on a raw
pointer requires an <code>unsafe</code> block, as shown in Listing 19-3:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let mut num = 5;

let r1 = &amp;num as *const i32;
let r2 = &amp;mut num as *mut i32;

unsafe {
    println!(&quot;r1 is: {}&quot;, *r1);
    println!(&quot;r2 is: {}&quot;, *r2);
}

#}</code></pre></pre>
<p><span class="caption">Listing 19-3: Dereferencing raw pointers within an
<code>unsafe</code> block</span></p>
<p>Creating a pointer can't do any harm; it's only when accessing the value that
it points at that you might end up dealing with an invalid value.</p>
<p>Note also that in Listing 19-1 and 19-3 we created a <code>*const i32</code> and a <code>*mut i32</code> that both pointed to the same memory location, that of <code>num</code>. If we had
tried to create an immutable and a mutable reference to <code>num</code> instead of raw
pointers, this would not have compiled due to the rule that says we can't have
a mutable reference at the same time as any immutable references. With raw
pointers, we are able to create a mutable pointer and an immutable pointer to
the same location, and change data through the mutable pointer, potentially
creating a data race. Be careful!</p>
<p>With all of these dangers, why would we ever use raw pointers? One major use
case is interfacing with C code, as we'll see in the next section on unsafe
functions. Another case is to build up safe abstractions that the borrow
checker doesn't understand. Let's introduce unsafe functions then look at an
example of a safe abstraction that uses unsafe code.</p>
<a class="header" href="ch19-01-unsafe-rust.html#calling-an-unsafe-function-or-method" id="calling-an-unsafe-function-or-method"><h3>Calling an Unsafe Function or Method</h3></a>
<p>The second operation that requires an unsafe block is calling an unsafe
function. Unsafe functions and methods look exactly like regular functions and
methods, but they have an extra <code>unsafe</code> out front. Bodies of unsafe functions
are effectively <code>unsafe</code> blocks. Here's an unsafe function named <code>dangerous</code>:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
unsafe fn dangerous() {}

unsafe {
    dangerous();
}

#}</code></pre></pre>
<p>If we try to call <code>dangerous</code> without the <code>unsafe</code> block, we'll get an error:</p>
<pre><code class="language-text">error[E0133]: call to unsafe function requires unsafe function or block
 --&gt; &lt;anon&gt;:4:5
  |
4 |     dangerous();
  |     ^^^^^^^^^^^ call to unsafe function
</code></pre>
<p>By inserting the <code>unsafe</code> block around our call to <code>dangerous</code>, we're asserting
to Rust that we've read the documentation for this function, we understand how
to use it properly, and we've verified that everything is correct.</p>
<a class="header" href="ch19-01-unsafe-rust.html#creating-a-safe-abstraction-over-unsafe-code" id="creating-a-safe-abstraction-over-unsafe-code"><h4>Creating a Safe Abstraction Over Unsafe Code</h4></a>
<p>As an example, let's check out some functionality from the standard library,
<code>split_at_mut</code>, and explore how we might implement it ourselves. This safe
method is defined on mutable slices, and it takes one slice and makes it into
two by splitting the slice at the index given as an argument, as demonstrated
in Listing 19-4:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];

let r = &amp;mut v[..];

let (a, b) = r.split_at_mut(3);

assert_eq!(a, &amp;mut [1, 2, 3]);
assert_eq!(b, &amp;mut [4, 5, 6]);

#}</code></pre></pre>
<p><span class="caption">Listing 19-4: Using the safe <code>split_at_mut</code>
function</span></p>
<p>This function can't be implemented using only safe Rust. An attempt might look
like Listing 19-5. For simplicity, we're implementing <code>split_at_mut</code> as a
function rather than a method, and only for slices of <code>i32</code> values rather than
for a generic type <code>T</code>:</p>
<pre><code class="language-rust ignore">fn split_at_mut(slice: &amp;mut [i32], mid: usize) -&gt; (&amp;mut [i32], &amp;mut [i32]) {
    let len = slice.len();

    assert!(mid &lt;= len);

    (&amp;mut slice[..mid],
     &amp;mut slice[mid..])
}
</code></pre>
<p><span class="caption">Listing 19-5: An attempted implementation of
<code>split_at_mut</code> using only safe Rust</span></p>
<p>This function first gets the total length of the slice, then asserts that the
index given as a parameter is within the slice by checking that the parameter
is less than or equal to the length. The assertion means that if we pass an
index that's greater than the length of the slice to split at, the function
will panic before it attempts to use that index.</p>
<p>Then we return two mutable slices in a tuple: one from the start of the initial
slice to the <code>mid</code> index, and another from <code>mid</code> to the end of the slice.</p>
<p>If we try to compile this, we'll get an error:</p>
<pre><code class="language-text">error[E0499]: cannot borrow `*slice` as mutable more than once at a time
 --&gt; &lt;anon&gt;:6:11
  |
5 |     (&amp;mut slice[..mid],
  |           ----- first mutable borrow occurs here
6 |      &amp;mut slice[mid..])
  |           ^^^^^ second mutable borrow occurs here
7 | }
  | - first borrow ends here
</code></pre>
<p>Rust's borrow checker can't understand that we're borrowing different parts of
the slice; it only knows that we're borrowing from the same slice twice.
Borrowing different parts of a slice is fundamentally okay; our two <code>&amp;mut [i32]</code>s aren't overlapping. However, Rust isn't smart enough to know this. When
we know something is okay, but Rust doesn't, it's time to reach for unsafe code.</p>
<p>Listing 19-6 shows how to use an <code>unsafe</code> block, a raw pointer, and some calls
to unsafe functions to make the implementation of <code>split_at_mut</code> work:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
use std::slice;

fn split_at_mut(slice: &amp;mut [i32], mid: usize) -&gt; (&amp;mut [i32], &amp;mut [i32]) {
    let len = slice.len();
    let ptr = slice.as_mut_ptr();

    assert!(mid &lt;= len);

    unsafe {
        (slice::from_raw_parts_mut(ptr, mid),
         slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
    }
}

#}</code></pre></pre>
<p><span class="caption">Listing 19-6: Using unsafe code in the implementation of
the <code>split_at_mut</code> function</span></p>
<p>Recall from Chapter 4 that slices are a pointer to some data and the length of
the slice. We've often used the <code>len</code> method to get the length of a slice; we
can use the <code>as_mut_ptr</code> method to get access to the raw pointer of a slice. In
this case, since we have a mutable slice to <code>i32</code> values, <code>as_mut_ptr</code> returns
a raw pointer with the type <code>*mut i32</code>, which we've stored in the variable
<code>ptr</code>.</p>
<p>The assertion that the <code>mid</code> index is within the slice stays the same. Then,
the <code>slice::from_raw_parts_mut</code> function does the reverse from the <code>as_mut_ptr</code>
and <code>len</code> methods: it takes a raw pointer and a length and creates a slice. We
call <code>slice::from_raw_parts_mut</code> to create a slice that starts from <code>ptr</code> and is
<code>mid</code> items long. Then we call the <code>offset</code> method on <code>ptr</code> with <code>mid</code> as an
argument to get a raw pointer that starts at <code>mid</code>, and we create a slice using
that pointer and the remaining number of items after <code>mid</code> as the length.</p>
<p>Because slices are checked, they're safe to use once we've created them. The
function <code>slice::from_raw_parts_mut</code> is an unsafe function because it takes a
raw pointer and trusts that this pointer is valid. The <code>offset</code> method on raw
pointers is also unsafe, since it trusts that the location some offset after a
raw pointer is also a valid pointer. We've put an <code>unsafe</code> block around our
calls to <code>slice::from_raw_parts_mut</code> and <code>offset</code> to be allowed to call them,
and we can tell by looking at the code and by adding the assertion that <code>mid</code>
must be less than or equal to <code>len</code> that all the raw pointers used within the
<code>unsafe</code> block will be valid pointers to data within the slice. This is an
acceptable and appropriate use of <code>unsafe</code>.</p>
<p>Note that the resulting <code>split_at_mut</code> function is safe: we didn't have to add
the <code>unsafe</code> keyword in front of it, and we can call this function from safe
Rust. We've created a safe abstraction to the unsafe code by writing an
implementation of the function that uses <code>unsafe</code> code in a safe way by only
creating valid pointers from the data this function has access to.</p>
<p>In contrast, the use of <code>slice::from_raw_parts_mut</code> in Listing 19-7 would
likely crash when the slice is used. This code takes an arbitrary memory
location and creates a slice ten thousand items long:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
use std::slice;

let address = 0x012345;
let r = address as *mut i32;

let slice = unsafe {
    slice::from_raw_parts_mut(r, 10000)
};

#}</code></pre></pre>
<p><span class="caption">Listing 19-7: Creating a slice from an arbitrary memory
location</span></p>
<p>We don't own the memory at this arbitrary location, and there's no guarantee
that the slice this code creates contains valid <code>i32</code> values. Attempting to use
<code>slice</code> as if it was a valid slice would be undefined behavior.</p>
<a class="header" href="ch19-01-unsafe-rust.html#extern--functions-for-calling-external-code-are-unsafe" id="extern--functions-for-calling-external-code-are-unsafe"><h4><code>extern</code>  Functions for Calling External Code are Unsafe</h4></a>
<p>Sometimes, your Rust code may need to interact with code written in another
language. To do this, Rust has a keyword, <code>extern</code>, that facilitates creating
and using a <em>Foreign Function Interface</em> (FFI). Listing 19-8 demonstrates how
to set up an integration with a function named <code>some_function</code> defined in an
external library written in a language other than Rust. Functions declared
within <code>extern</code> blocks are always unsafe to call from Rust code:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust ignore">extern &quot;C&quot; {
    fn some_function();
}

fn main() {
    unsafe { some_function() };
}
</code></pre>
<p><span class="caption">Listing 19-8: Declaring and calling an <code>extern</code> function
defined in another language</span></p>
<p>Within the <code>extern &quot;C&quot;</code> block, we list the names and signatures of functions
defined in a library written in another language that we want to be able to
call.<code>&quot;C&quot;</code> defines which <em>application binary interface</em> (ABI) the external
function uses. The ABI defines how to call the function at the assembly level.
The <code>&quot;C&quot;</code> ABI is the most common, and follows the C programming language's ABI.</p>
<p>Calling an external function is always unsafe. If we're calling into some other
language, that language does not enforce Rust's safety guarantees. Since Rust
can't check that the external code is safe, we are responsible for checking the
safety of the external code and indicating we have done so by using an <code>unsafe</code>
block to call external functions.</p>
<!-- PROD: START BOX -->
<a class="header" href="ch19-01-unsafe-rust.html#calling-rust-functions-from-other-languages" id="calling-rust-functions-from-other-languages"><h5>Calling Rust Functions from Other Languages</h5></a>
<p>The <code>extern</code> keyword is also used for creating an interface that allows other
languages to call Rust functions. Instead of an <code>extern</code> block, we can add the
<code>extern</code> keyword and specifying the ABI to use just before the <code>fn</code> keyword. We
also add the <code>#[no_mangle]</code> annotation to tell the Rust compiler not to mangle
the name of this function. The <code>call_from_c</code> function in this example would be
accessible from C code, once we've compiled to a shared library and linked from
C:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
#[no_mangle]
pub extern &quot;C&quot; fn call_from_c() {
    println!(&quot;Just called a Rust function from C!&quot;);
}

#}</code></pre></pre>
<p>This usage of <code>extern</code> does not require <code>unsafe</code></p>
<!-- PROD: END BOX -->
<a class="header" href="ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable" id="accessing-or-modifying-a-mutable-static-variable"><h3>Accessing or Modifying a Mutable Static Variable</h3></a>
<p>We've gone this entire book without talking about <em>global variables</em>. Many
programming languages support them, and so does Rust. However, global variables
can be problematic: for example, if you have two threads accessing the same
mutable global variable, a data race can happen.</p>
<p>Global variables are called <em>static</em> in Rust. Listing 19-9 shows an example
declaration and use of a static variable with a string slice as a value:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust">static HELLO_WORLD: &amp;str = &quot;Hello, world!&quot;;

fn main() {
    println!(&quot;name is: {}&quot;, HELLO_WORLD);
}
</code></pre></pre>
<p><span class="caption">Listing 19-9: Defining and using an immutable static
variable</span></p>
<p><code>static</code> variables are similar to constants: their names are also in
<code>SCREAMING_SNAKE_CASE</code> by convention, and we <em>must</em> annotate the variable's
type, which is <code>&amp;'static str</code> in this case. Only references with the <code>'static</code>
lifetime may be stored in a static variable. Because of this, the Rust compiler
can figure out the lifetime by itself and we don't need to annotate it explicitly.
Accessing immutable static variables is safe. Values in a static variable have a
fixed address in memory, and using the value will always access the same data.
Constants, on the other hand, are allowed to duplicate their data whenever they
are used.</p>
<p>Another way in which static variables are different from constants is that
static variables can be mutable. Both accessing and modifying mutable static
variables is unsafe. Listing 19-10 shows how to declare, access, and modify a
mutable static variable named <code>COUNTER</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><pre class="playpen"><code class="language-rust">static mut COUNTER: u32 = 0;

fn add_to_count(inc: u32) {
    unsafe {
        COUNTER += inc;
    }
}

fn main() {
    add_to_count(3);

    unsafe {
        println!(&quot;COUNTER: {}&quot;, COUNTER);
    }
}
</code></pre></pre>
<p><span class="caption">Listing 19-10: Reading from or writing to a mutable
static variable is unsafe</span></p>
<p>Just like with regular variables, we specify that a static variable should be
mutable using the <code>mut</code> keyword. Any time that we read or write from <code>COUNTER</code>
has to be within an <code>unsafe</code> block. This code compiles and prints <code>COUNTER: 3</code>
as we would expect since it's single threaded, but having multiple threads
accessing <code>COUNTER</code> would likely result in data races.</p>
<p>Mutable data that is globally accessible is difficult to manage and ensure that
there are no data races, which is why Rust considers mutable static variables
to be unsafe. If possible, prefer using the concurrency techniques and
threadsafe smart pointers we discussed in Chapter 16 to have the compiler check
that data accessed from different threads is done safely.</p>
<a class="header" href="ch19-01-unsafe-rust.html#implementing-an-unsafe-trait" id="implementing-an-unsafe-trait"><h3>Implementing an Unsafe Trait</h3></a>
<p>Finally, the last action we're only allowed to take when we use the <code>unsafe</code>
keyword is implementing an unsafe trait. We can declare that a trait is
<code>unsafe</code> by adding the <code>unsafe</code> keyword before <code>trait</code>, and then implementing
the trait must be marked as <code>unsafe</code> too, as shown in Listing 19-11:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
unsafe trait Foo {
    // methods go here
}

unsafe impl Foo for i32 {
    // method implementations go here
}

#}</code></pre></pre>
<p><span class="caption">Listing 19-11: Defining and implementing an unsafe
trait</span></p>
<p>Like unsafe functions, methods in an unsafe trait have some invariant that the
compiler cannot verify. By using <code>unsafe impl</code>, we're promising that we'll
uphold these invariants.</p>
<p>As an example, recall the <code>Sync</code> and <code>Send</code> marker traits from Chapter 16, and
that the compiler implements these automatically if our types are composed
entirely of <code>Send</code> and <code>Sync</code> types. If we implement a type that contains
something that's not <code>Send</code> or <code>Sync</code> such as raw pointers, and we want to mark
our type as <code>Send</code> or <code>Sync</code>, that requires using <code>unsafe</code>. Rust can't verify
that our type upholds the guarantees that a type can be safely sent across
threads or accessed from multiple threads, so we need to do those checks
ourselves and indicate as such with <code>unsafe</code>.</p>
<p>Using <code>unsafe</code> to take one of these four actions isn't wrong or frowned upon,
but it is trickier to get <code>unsafe</code> code correct since the compiler isn't able
to help uphold memory safety. When you have a reason to use <code>unsafe</code> code,
however, it's possible to do so, and having the explicit <code>unsafe</code> annotation
makes it easier to track down the source of problems if they occur.</p>

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="ch19-00-advanced-features.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="ch19-02-advanced-lifetimes.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="ch19-00-advanced-features.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="ch19-02-advanced-lifetimes.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>