mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:24:32 -06:00
294 lines
15 KiB
HTML
294 lines
15 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>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">
|
||
|
||
<!-- 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>
|
||
<!-- 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="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><strong>2.</strong> Tutorial</li><li><a href="up-and-running.html"><strong>3.</strong> Up and Running</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="scalar-types.html"><strong>3.3.</strong> Scalar Types</a></li><li><a href="compound-types.html"><strong>3.4.</strong> Compound Types</a></li><li><a href="comments.html"><strong>3.5.</strong> Comments</a></li><li><a href="if.html"><strong>3.6.</strong> Control flow with <code>if</code></a></li><li><a href="loops.html"><strong>3.7.</strong> Loops</a></li></ul></li><li><a href="understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="structs.html" class="active"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li><li><strong>5.2.</strong> Generics</li><li><strong>5.3.</strong> Advanced</li></ul></li><li><strong>6.</strong> Enums</li><li><ul class="section"><li><strong>6.1.</strong> Match</li><li><strong>6.2.</strong> Patterns</li><li><strong>6.3.</strong> Option</li><li><strong>6.4.</strong> if let</li></ul></li><li><strong>7.</strong> Crates & Modules</li><li><strong>8.</strong> Error Handling</li><li><strong>9.</strong> Basic Collections</li><li><ul class="section"><li><strong>9.1.</strong> Vectors</li><li><strong>9.2.</strong> Strings</li><li><strong>9.3.</strong> <code>HashMap<K, V></code></li></ul></li><li><strong>10.</strong> Lifetimes</li><li><strong>11.</strong> Traits</li><li><strong>12.</strong> Closures</li><li><strong>13.</strong> Iterators</li><li><strong>14.</strong> I/O</li><li><ul class="section"><li><strong>14.1.</strong> <code>Read</code> & <code>Write</code></li><li><strong>14.2.</strong> <code>std::fs</code></li><li><strong>14.3.</strong> <code>std::path</code></li><li><strong>14.4.</strong> <code>std::env</code></li></ul></li><li><strong>15.</strong> Testing</li><li><strong>16.</strong> Smart Pointers</li><li><ul class="section"><li><strong>16.1.</strong> <code>Deref</code></li><li><strong>16.2.</strong> <code>Deref</code> coercions</li><li><strong>16.3.</strong> <code>Box<T></code></li><li><strong>16.4.</strong> <code>Rc<T></code></li></ul></li><li><strong>17.</strong> Concurrency</li><li><ul class="section"><li><strong>17.1.</strong> Threads</li><li><strong>17.2.</strong> <code>Send</code> & <code>Sync</code></li><li><strong>17.3.</strong> <code>Arc<T></code></li><li><strong>17.4.</strong> <code>Mutex<T></code></li><li><strong>17.5.</strong> <code>Channels</code></li></ul></li><li><strong>18.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>18.1.</strong> Raw Pointers</li><li><strong>18.2.</strong> transmute</li></ul></li><li><strong>19.</strong> FFI</li><li><ul class="section"><li><strong>19.1.</strong> Conditional Compilation</li><li><strong>19.2.</strong> Bindings to C</li><li><strong>19.3.</strong> Using Rust from Other Languages</li><li><strong>19.4.</strong> <code>static</code></li></ul></li><li><strong>20.</strong> Cargo</li><li><ul class="section"><li><strong>20.1.</strong> Crates.io</li></ul></li><li><strong>21.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>21.1.</strong> Associated Types</li><li><strong>21.2.</strong> Trait Objects</li><li><strong>21.3.</strong> UFCS</li><li><strong>21.4.</strong> Coherence</li></ul></li><li><strong>22.</strong> Interior mutability</li><li><ul class="section"><li><strong>22.1.</strong> <code>Cell<T></code></li><li><strong>22.2.</strong> <code>RefCell<T></code></li></ul></li><li><strong>23.</strong> Macros</li><li><strong>24.</strong> Nightly Rust</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">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">
|
||
<h1>Structs</h1>
|
||
<p>So far, all of the data types we’ve seen allow us to have a single value
|
||
at a time. <code>struct</code>s give us the ability to package up multiple values and
|
||
keep them in one related structure.</p>
|
||
<p>Let’s write a program which calculates the distance between two points.
|
||
We’ll start off with single variable bindings, and then refactor it to
|
||
use <code>struct</code>s instead.</p>
|
||
<p>Let’s make a new project with Cargo:</p>
|
||
<pre><code class="language-bash">$ cargo new --bin points
|
||
$ cd points
|
||
</code></pre>
|
||
<p>Here’s a short program which calculates the distance between two points. Put
|
||
it into your <code>src/main.rs</code>:</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x1 = 0.0;
|
||
let y1 = 5.0;
|
||
|
||
let x2 = 12.0;
|
||
let y2 = 0.0;
|
||
|
||
let answer = distance(x1, y1, x2, y2);
|
||
|
||
println!("Point 1: ({}, {})", x1, y1);
|
||
println!("Point 2: ({}, {})", x2, y2);
|
||
println!("Distance: {}", answer);
|
||
}
|
||
|
||
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||
let x_squared = f64::powi(x2 - x1, 2);
|
||
let y_squared = f64::powi(y2 - y1, 2);
|
||
|
||
f64::sqrt(x_squared + y_squared)
|
||
}
|
||
</code></pre>
|
||
<p>Let's try running this program with <code>cargo run</code>:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling points v0.1.0 (file:///projects/points)
|
||
Running `target/debug/points`
|
||
Point 1: (0, 5)
|
||
Point 2: (12, 0)
|
||
Distance: 13
|
||
</code></pre>
|
||
<p>Let's take a quick look at <code>distance()</code> before we move forward:</p>
|
||
<pre><code class="language-rust">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||
let x_squared = f64::powi(x2 - x1, 2);
|
||
let y_squared = f64::powi(y2 - y1, 2);
|
||
|
||
f64::sqrt(x_squared + y_squared)
|
||
}
|
||
</code></pre>
|
||
<p>To find the distance between two points, we can use the Pythagorean Theorem.
|
||
The theorem is named after Pythagoras, who was the first person to mathematically
|
||
prove this formula. The details aren't that important, to be honest. There's a few
|
||
things that we haven't discussed yet, though.</p>
|
||
<pre><code class="language-rust,ignore">f64::powi(2.0, 3)
|
||
</code></pre>
|
||
<p>The double colon (<code>::</code>) here is a namespace operator. We haven’t talked about
|
||
modules yet, but you can think of the <code>powi()</code> function as being scoped inside
|
||
of another name. In this case, the name is <code>f64</code>, the same as the type. The
|
||
<code>powi()</code> function takes two arguments: the first is a number, and the second is
|
||
the power that it raises that number to. In this case, the second number is an
|
||
integer, hence the ‘i’ in its name. Similarly, <code>sqrt()</code> is a function under the
|
||
<code>f64</code> module, which takes the square root of its argument.</p>
|
||
<h2>Why <code>struct</code>s?</h2>
|
||
<p>Our little program is okay, but we can do better. The key is in the signature
|
||
of <code>distance()</code>:</p>
|
||
<pre><code class="language-rust,ignore">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
|
||
</code></pre>
|
||
<p>The distance function is supposed to calculate the distance between two points.
|
||
But our distance function calculates some distance between four numbers. The
|
||
first two and last two arguments are related, but that’s not expressed anywhere
|
||
in our program itself. We need a way to group <code>(x1, y1)</code> and <code>(x2, y2)</code>
|
||
together.</p>
|
||
<p>We’ve already discussed one way to do that: tuples. Here’s a version of our program
|
||
which uses tuples:</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let p1 = (0.0, 5.0);
|
||
|
||
let p2 = (12.0, 0.0);
|
||
|
||
let answer = distance(p1, p2);
|
||
|
||
println!("Point 1: {:?}", p1);
|
||
println!("Point 2: {:?}", p2);
|
||
println!("Distance: {}", answer);
|
||
}
|
||
|
||
fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
|
||
let x_squared = f64::powi(p2.0 - p1.0, 2);
|
||
let y_squared = f64::powi(p2.1 - p1.1, 2);
|
||
|
||
f64::sqrt(x_squared + y_squared)
|
||
}
|
||
</code></pre>
|
||
<p>This is a little better, for sure. Tuples let us add a little bit of structure.
|
||
We’re now passing two arguments, so that’s more clear. But it’s also worse.
|
||
Tuples don’t give names to their elements, and so our calculation has gotten
|
||
much more confusing:</p>
|
||
<pre><code class="language-rust,ignore">p2.0 - p1.0
|
||
p2.1 - p1.1
|
||
</code></pre>
|
||
<p>When writing this example, your authors almost got it wrong themselves! Distance
|
||
is all about <code>x</code> and <code>y</code> points, but now it’s all about <code>0</code> and <code>1</code>. This isn’t
|
||
great.</p>
|
||
<p>Enter <code>struct</code>s. We can transform our tuples into something with a name:</p>
|
||
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
|
||
|
||
struct Point {
|
||
x: f64,
|
||
y: f64,
|
||
}
|
||
|
||
let p1 = Point { x: 0.0, y: 5.0 };
|
||
</code></pre>
|
||
<p>Here’s what declaring a <code>struct</code> looks like:</p>
|
||
<pre><code class="language-text">struct NAME {
|
||
NAME: TYPE,
|
||
}
|
||
</code></pre>
|
||
<p>The <code>NAME: TYPE</code> bit is called a ‘field’, and we can have as many or as few of
|
||
them as you’d like. If you have none of them, drop the <code>{}</code>s:</p>
|
||
<pre><code class="language-rust">struct Foo;
|
||
</code></pre>
|
||
<p><code>struct</code>s with no fields are called ‘unit structs’, and are used in certain
|
||
advanced situations. We will just ignore them for now.</p>
|
||
<p>You can access the field of a struct in the same way you access an element of
|
||
a tuple, except you use its name:</p>
|
||
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
|
||
let x = p1.0;
|
||
|
||
struct Point {
|
||
x: f64,
|
||
y: f64,
|
||
}
|
||
|
||
let p1 = Point { x: 0.0, y: 5.0 };
|
||
let x = p1.x;
|
||
</code></pre>
|
||
<p>Let’s convert our program to use our <code>Point</code> <code>struct</code>. Here’s what it looks
|
||
like now:</p>
|
||
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
|
||
struct Point {
|
||
x: f64,
|
||
y: f64,
|
||
}
|
||
|
||
fn main() {
|
||
let p1 = Point { x: 0.0, y: 5.0};
|
||
|
||
let p2 = Point { x: 12.0, y: 0.0};
|
||
|
||
let answer = distance(p1, p2);
|
||
|
||
println!("Point 1: {:?}", p1);
|
||
println!("Point 2: {:?}", p2);
|
||
println!("Distance: {}", answer);
|
||
}
|
||
|
||
fn distance(p1: Point, p2: Point) -> f64 {
|
||
let x_squared = f64::powi(p2.x - p1.x, 2);
|
||
let y_squared = f64::powi(p2.y - p1.y, 2);
|
||
|
||
f64::sqrt(x_squared + y_squared)
|
||
}
|
||
</code></pre>
|
||
<p>Our function signature for <code>distance()</code> now says exactly what we mean: it
|
||
calculates the distance between two <code>Point</code>s. And rather than <code>0</code> and <code>1</code>,
|
||
we’ve got back our <code>x</code> and <code>y</code>. This is a win for clarity.</p>
|
||
<p>There’s one other thing that’s a bit strange here, this annotation on our
|
||
<code>struct</code> declaration:</p>
|
||
<pre><code class="language-rust,ignore">#[derive(Debug,Copy,Clone)]
|
||
struct Point {
|
||
</code></pre>
|
||
<p>We haven’t yet talked about traits, but we did talk about <code>Debug</code> when we
|
||
discussed arrays. This <code>derive</code> attribute allows us to tweak the behavior of
|
||
our <code>Point</code>. In this case, we are opting into copy semantics, and everything
|
||
that implements <code>Copy</code> must implement <code>Clone</code>.</p>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="slices.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="method-syntax.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="slices.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="method-syntax.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>
|