Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Hash implementation to time::Timespec #15825

Closed
wants to merge 115 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
115 commits
Select commit Hold shift + click to select a range
c649204
Define a new setting g:rust_fold
lilyball Jul 6, 2014
94cfd1b
Set softtabstop, textwidth, and optionally colorcolumn
lilyball Jul 6, 2014
9dc667d
Remove rust_colorcolumn, set textwidth to 99
lilyball Jul 8, 2014
407fe9a
mandelbrot: fix overlapping buffers
Ryman Jul 13, 2014
1675339
Fix cargo install instructions
steveklabnik Jul 15, 2014
154ca08
use trait rather than fns
jbclements Jul 14, 2014
ca05828
change to new trait style for method field refs
jbclements Jul 14, 2014
0a31060
Support for specifying the code model
Zoxc Jul 15, 2014
711e439
mk: Fix LD_LIBRARY_PATH_ENV_NAMES in cross build
klutzy Jul 14, 2014
778529b
obsolete.rs: fix typo in message
Jul 15, 2014
be1fe29
rustc.1: fix typo
Jul 15, 2014
a1def08
complement-lang-faq.md: fix typos
Jul 15, 2014
83fe455
debuginfo: Add python formatters that allow LLDB to print values with…
michaelwoerister Jul 9, 2014
ba287f6
debuginfo: Inject 'Rust-mode' LLDB prelude into debuginfo test scripts.
michaelwoerister Jul 9, 2014
b56ef79
debuginfo: Remove atexit()-debugger shutdown from lldb_batchmode.py
michaelwoerister Jul 9, 2014
c7f45a9
debuginfo: Add LLDB autotests to debuginfo test suite.
michaelwoerister Jul 9, 2014
3b336b2
debuginfo: Make sure that only one LLDB test task is run at a time.
michaelwoerister Jul 9, 2014
731f44d
debuginfo: Don't crash when encountering global variable with unknown…
michaelwoerister Jul 10, 2014
efbbb51
auto merge of #15691 : jbclements/rust/method-field-cleanup, r=alexcr…
bors Jul 16, 2014
036b9e8
Add an option to disable the use of the redzone
Zoxc Jul 16, 2014
0582421
auto merge of #15693 : steveklabnik/rust/guide_fix_cargo, r=cmr
bors Jul 16, 2014
5f843ee
Examples for Integer trait methods.
treeman Jul 16, 2014
428c7bc
Main example for bigint usage.
treeman Jul 16, 2014
80ef6b8
Extend HashSet documentation.
treeman Jul 14, 2014
316719e
auto merge of #15476 : kballard/rust/more_vim_tweaks, r=chris
bors Jul 16, 2014
175f113
auto merge of #15573 : michaelwoerister/rust/lldb-tests-rebased-09-Ju…
bors Jul 16, 2014
7beb550
Improve docs on JSON.
errordeveloper Jul 14, 2014
06c7ee9
auto merge of #15667 : treeman/rust/set-doc, r=alexcrichton
bors Jul 16, 2014
81b69d1
stability lint: ignore code from macro expansion
aturon Jul 16, 2014
b35d1a8
Implement Index and IndexMut for Vec
nrc Jul 13, 2014
1565df1
btree: use pattern matching instead of unwrap
fhahn Jul 16, 2014
d3adccd
auto merge of #15696 : Zoxc/rust/redzone, r=alexcrichton
bors Jul 16, 2014
ace3a77
Add TreeSet example.
steveklabnik Jul 16, 2014
aa760a8
deprecate Vec::get
nrc Jul 14, 2014
459ffc2
auto merge of #15652 : nick29581/rust/vec_index, r=acrichto
bors Jul 17, 2014
eddc3cc
syntax: Add ToTokens for Option<T>
bgamari Jul 17, 2014
8659889
syntax: Add ToTokens for Attribute_
bgamari Jul 17, 2014
96072d6
syntax: Generalize ToTokens impl for Vec<T>
bgamari Jul 17, 2014
357d5cd
librustc: Implement the fully-expanded, UFCS form of explicit self.
pcwalton May 6, 2014
fe49cbe
libsyntax: Remove `Send` from `PtrTy` in `deriving`.
pcwalton Jul 8, 2014
99bd926
Disallow importing from types when reexport is involved
sanxiyn Jul 17, 2014
a807aa1
syntax: Add quote_method!
bgamari Jul 17, 2014
00c70d1
librustc: Allow the new UFCS explicit self in trait definitions, and
pcwalton Jul 8, 2014
32cb44b
auto merge of #14022 : pcwalton/rust/explicit-self, r=pnkfelix
bors Jul 17, 2014
9fc8394
auto merge of #15668 : steveklabnik/rust/tree_set_example, r=alexcric…
bors Jul 17, 2014
46a3314
lint: add method to get level of a specific lint.
huonw Jul 17, 2014
dd348b3
auto merge of #15698 : Zoxc/rust/code-model, r=alexcrichton
bors Jul 17, 2014
e4f8cec
syntax: Add ToTokens impl for Method
bgamari Jul 17, 2014
c0e6c4e
auto merge of #15675 : errordeveloper/rust/json_docs, r=steveklabnik
bors Jul 17, 2014
89e28d3
Small fixes for tutorial.
treeman Jul 17, 2014
8107ef7
Rename functions in the CloneableVector trait
aochagavia Jul 16, 2014
92b5bf8
auto merge of #15705 : klutzy/rust/cross-ld-library, r=alexcrichton
bors Jul 17, 2014
c4b1077
auto merge of #15706 : phi-gamma/rust/master, r=huonw
bors Jul 17, 2014
d6b42c2
str: Add better tests for string slice's Chars iterator
Jul 17, 2014
42357d7
core::str: Implement Chars iterator using slice::Items
Jul 17, 2014
ca24abd
auto merge of #15716 : treeman/rust/bigint-doc, r=alexcrichton
bors Jul 17, 2014
36d6acc
auto merge of #15718 : treeman/rust/integer-doc, r=alexcrichton
bors Jul 17, 2014
de70d76
librustc: Remove cross-borrowing of `Box<T>` to `&T` from the language,
pcwalton Jul 7, 2014
e288fc6
auto merge of #15515 : pcwalton/rust/cross-borrowing, r=alexcrichton
bors Jul 17, 2014
9e59c76
Add more tests for str Chars iterator
Jul 17, 2014
f50e4ee
auto merge of #15719 : michaelwoerister/rust/global_var_null_span_fix…
bors Jul 18, 2014
226b7d1
Guide: strings
steveklabnik Jul 17, 2014
31eb00c
sync: Ensure try_send() wakes up receivers
alexcrichton Jul 18, 2014
cebed8a
auto merge of #15593 : steveklabnik/rust/string_guide, r=kballard
bors Jul 18, 2014
7ee45aa
Add examples for DList methods rotate_forward, rotate_backward, appen…
nham Jul 17, 2014
8a308b1
auto merge of #15725 : aochagavia/rust/vec, r=alexcrichton
bors Jul 18, 2014
8067d03
auto merge of #15726 : aturon/rust/macro-stability, r=alexcrichton
bors Jul 18, 2014
5980aa0
auto merge of #15727 : fhahn/rust/remove-some-unwraps, r=alexcrichton
bors Jul 18, 2014
d9f1d6b
auto merge of #15732 : bgamari/rust/to-tokens, r=alexcrichton
bors Jul 18, 2014
fc4f6ed
Removed `index_to_bitset` from the dataflow context.
pnkfelix Jul 17, 2014
8f50428
Removed the `_frozen` methods from dataflow API.
pnkfelix Jul 17, 2014
4418664
auto merge of #15733 : sanxiyn/rust/use-from-type, r=alexcrichton
bors Jul 18, 2014
b2a02b5
Fill in documentation for HashSet.
treeman Jul 17, 2014
5ddc7b4
auto merge of #15737 : huonw/rust/lint-level-here, r=pnkfelix
bors Jul 18, 2014
01b6fd3
Remove examples from trait implementations. Unhide imports.
treeman Jul 18, 2014
0c30e1f
Include Strings guide with the others.
steveklabnik Jul 18, 2014
50868db
rustc: #[crate_name] and --crate-name must match
alexcrichton Jul 15, 2014
02adaca
librustc: Implement unboxed closures with mutable receivers
pcwalton May 29, 2014
33a4dd8
Remove outdated unreachable check from `call_visit_glue`
dotdash Jul 6, 2014
9c9bdfd
auto merge of #14539 : pcwalton/rust/unboxed-closures, r=pnkfelix
bors Jul 18, 2014
18717fc
Correct plural of arguments in format_args!
treeman Jul 18, 2014
5274e99
Assign more diagnostic codes
Jul 17, 2014
7502b4c
auto merge of #15742 : pnkfelix/rust/fsk-fix-15019, r=pcwalton
bors Jul 18, 2014
820a558
Special case for 0 arguments given in format!
treeman Jul 18, 2014
cb404dd
librustc: Emit enum variant constructor at callsite instead of via a …
luqmana Jul 10, 2014
06bf73a
librustc: Emit tuple struct constructor at callsite instead of via a …
luqmana Jul 10, 2014
27748b0
librustc: Only emit constructor functions as necessary.
luqmana Jul 10, 2014
ad27e26
librustc: Set enum discriminant only after field translation.
luqmana Jul 10, 2014
61ded48
Ignore one test.
luqmana Jul 18, 2014
d368ffd
Remove the unneeded final parameter from call_visit_glue
dotdash Jul 18, 2014
ef352fa
auto merge of #15743 : Ryman/rust/mandelbrot_fix, r=alexcrichton
bors Jul 18, 2014
bbb299a
Clarify str Chars iterator implementation
Jul 17, 2014
4592164
Write multibyte case for str Chars iterator in-line
Jul 18, 2014
fba1194
Add support for patterns referencing non-trivial statics
Jul 13, 2014
82fb85a
rustc: Mix extra-filename in temp outputs
alexcrichton Jul 15, 2014
c8b8444
Improve documentation for rand::random
steveklabnik Jul 17, 2014
44a71de
auto merge of #15686 : alexcrichton/rust/same-crate-name, r=kballard
bors Jul 19, 2014
fb4c3f0
auto merge of #15752 : nham/rust/dlist_docs, r=alexcrichton
bors Jul 19, 2014
f05a2c9
auto merge of #15754 : jakub-/rust/diagnostics, r=alexcrichton
bors Jul 19, 2014
e0a6e2b
auto merge of #15765 : luqmana/rust/iec, r=pcwalton
bors Jul 19, 2014
c5e0736
Simplify str CharOffsets iterator
Jul 19, 2014
ca38434
auto merge of #15638 : blake2-ppc/rust/ptr-arithmetic-chars, r=huonw
bors Jul 19, 2014
793b142
auto merge of #15772 : treeman/rust/hashset-doc, r=alexcrichton
bors Jul 19, 2014
ab61022
auto merge of #15782 : steveklabnik/rust/string_guide_link, r=cmr
bors Jul 19, 2014
6f99a27
librustc: Implement lifetime elision.
pcwalton Jul 18, 2014
8672a23
auto merge of #15650 : jakub-/rust/patterns-statics, r=pcwalton
bors Jul 19, 2014
d8652de
auto merge of #15746 : steveklabnik/rust/docs_random, r=alexcrichton
bors Jul 19, 2014
5e0a597
auto merge of #15764 : alexcrichton/rust/issue-15761, r=kballard
bors Jul 20, 2014
56fafe2
auto merge of #15767 : pcwalton/rust/lifetime-elision, r=nick29581
bors Jul 20, 2014
707cf47
Register new snapshots
alexcrichton Jul 16, 2014
7d0a613
auto merge of #15776 : alexcrichton/rust/snapshots, r=huonw
bors Jul 20, 2014
320dbc1
auto merge of #15745 : treeman/rust/tutorial-fixup, r=steveklabnik
bors Jul 20, 2014
50481f5
auto merge of #15784 : dotdash/rust/unreach, r=luqmana
bors Jul 20, 2014
4f55b52
auto merge of #15785 : treeman/rust/fix-15780, r=alexcrichton
bors Jul 20, 2014
343a52f
small typo
steveklabnik Jul 20, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion man/rustc.1
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ AST nodes and blocks with IDs), or flowgraph=<nodeid> (graphviz
formatted flowgraph for node)
.TP
\fB\-\-dep-info\fR [FILENAME]
Output dependency info to <filename> after compiling, in o format suitable
Output dependency info to <filename> after compiling, in a format suitable
for use by Makefiles.
.TP
\fB\-\-sysroot\fR PATH
Expand Down
2 changes: 1 addition & 1 deletion mk/docs.mk
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ DOCS := index intro tutorial guide guide-ffi guide-macros guide-lifetimes \
guide-tasks guide-container guide-pointers guide-testing \
guide-runtime complement-bugreport \
complement-lang-faq complement-design-faq complement-project-faq rust \
rustdoc guide-unsafe
rustdoc guide-unsafe guide-strings

PDF_DOCS := tutorial rust

Expand Down
2 changes: 1 addition & 1 deletion mk/main.mk
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ define SREQ_CMDS
ifeq ($$(OSTYPE_$(3)),apple-darwin)
LD_LIBRARY_PATH_ENV_NAME$(1)_T_$(2)_H_$(3) := DYLD_LIBRARY_PATH
else
ifeq ($$(CFG_WINDOWSY_$(2)),1)
ifeq ($$(CFG_WINDOWSY_$(3)),1)
LD_LIBRARY_PATH_ENV_NAME$(1)_T_$(2)_H_$(3) := PATH
else
LD_LIBRARY_PATH_ENV_NAME$(1)_T_$(2)_H_$(3) := LD_LIBRARY_PATH
Expand Down
18 changes: 14 additions & 4 deletions src/compiletest/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use std::io::fs;
use std::from_str::FromStr;
use getopts::{optopt, optflag, reqopt};
use common::Config;
use common::{Pretty, DebugInfoGdb, Codegen};
use common::{Pretty, DebugInfoGdb, DebugInfoLldb, Codegen};
use util::logv;
use regex::Regex;

Expand Down Expand Up @@ -89,9 +89,9 @@ pub fn parse_config(args: Vec<String> ) -> Config {
optflag("h", "help", "show this message"));

assert!(!args.is_empty());
let argv0 = (*args.get(0)).clone();
let argv0 = args[0].clone();
let args_ = args.tail();
if args.get(1).as_slice() == "-h" || args.get(1).as_slice() == "--help" {
if args[1].as_slice() == "-h" || args[1].as_slice() == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!("");
Expand All @@ -116,7 +116,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
}

let filter = if !matches.free.is_empty() {
let s = matches.free.get(0).as_slice();
let s = matches.free[0].as_slice();
match regex::Regex::new(s) {
Ok(re) => Some(re),
Err(e) => {
Expand Down Expand Up @@ -241,6 +241,16 @@ pub fn run_tests(config: &Config) {
os::setenv("RUST_TEST_TASKS","1");
}

match config.mode {
DebugInfoLldb => {
// Some older versions of LLDB seem to have problems with multiple
// instances running in parallel, so only run one test task at a
// time.
os::setenv("RUST_TEST_TASKS", "1");
}
_ => { /* proceed */ }
}

let opts = test_opts(config);
let tests = make_tests(config);
// sadly osx needs some file descriptor limits raised for running tests in
Expand Down
34 changes: 22 additions & 12 deletions src/compiletest/runtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
let proc_res = print_source(config,
props,
testfile,
(*srcs.get(round)).to_string(),
srcs[round].to_string(),
"normal");

if !proc_res.status.success() {
Expand All @@ -187,9 +187,9 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
let s = File::open(&filepath).read_to_end().unwrap();
String::from_utf8(s).unwrap()
}
None => { (*srcs.get(srcs.len() - 2u)).clone() }
None => { srcs[srcs.len() - 2u].clone() }
};
let mut actual = (*srcs.get(srcs.len() - 1u)).clone();
let mut actual = srcs[srcs.len() - 1u].clone();

if props.pp_exact.is_some() {
// Now we have to care about line endings
Expand All @@ -209,7 +209,7 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
if props.no_pretty_expanded { return }

// additionally, run `--pretty expanded` and try to build it.
let proc_res = print_source(config, props, testfile, (*srcs.get(round)).clone(), "expanded");
let proc_res = print_source(config, props, testfile, srcs[round].clone(), "expanded");
if !proc_res.status.success() {
fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
}
Expand Down Expand Up @@ -536,6 +536,16 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
// We don't want to hang when calling `quit` while the process is still running
let mut script_str = String::from_str("settings set auto-confirm true\n");

// Make LLDB emit its version, so we have it documented in the test output
script_str.push_str("version\n");

// Switch LLDB into "Rust mode"
script_str.push_str("command script import ./src/etc/lldb_rust_formatters.py\n");
script_str.push_str("type summary add --no-value ");
script_str.push_str("--python-function lldb_rust_formatters.print_val ");
script_str.push_str("-x \".*\" --category Rust\n");
script_str.push_str("type category enable Rust\n");

// Set breakpoints on every line that contains the string "#break"
for line in breakpoint_lines.iter() {
script_str.push_str(format!("breakpoint set --line {}\n",
Expand Down Expand Up @@ -692,7 +702,7 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
let mut rest = line.trim();
let mut first = true;
let mut failed = false;
for frag in check_fragments.get(i).iter() {
for frag in check_fragments[i].iter() {
let found = if first {
if rest.starts_with(frag.as_slice()) {
Some(0)
Expand Down Expand Up @@ -742,7 +752,7 @@ fn check_error_patterns(props: &TestProps,
}

let mut next_err_idx = 0u;
let mut next_err_pat = props.error_patterns.get(next_err_idx);
let mut next_err_pat = &props.error_patterns[next_err_idx];
let mut done = false;
let output_to_check = if props.check_stdout {
format!("{}{}", proc_res.stdout, proc_res.stderr)
Expand All @@ -751,14 +761,14 @@ fn check_error_patterns(props: &TestProps,
};
for line in output_to_check.as_slice().lines() {
if line.contains(next_err_pat.as_slice()) {
debug!("found error pattern {}", *next_err_pat);
debug!("found error pattern {}", next_err_pat);
next_err_idx += 1u;
if next_err_idx == props.error_patterns.len() {
debug!("found all error patterns");
done = true;
break;
}
next_err_pat = props.error_patterns.get(next_err_idx);
next_err_pat = &props.error_patterns[next_err_idx];
}
}
if done { return; }
Expand Down Expand Up @@ -837,13 +847,13 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
for line in proc_res.stderr.as_slice().lines() {
let mut was_expected = false;
for (i, ee) in expected_errors.iter().enumerate() {
if !*found_flags.get(i) {
if !found_flags[i] {
debug!("prefix={} ee.kind={} ee.msg={} line={}",
prefixes.get(i).as_slice(),
prefixes[i].as_slice(),
ee.kind,
ee.msg,
line);
if prefix_matches(line, prefixes.get(i).as_slice()) &&
if prefix_matches(line, prefixes[i].as_slice()) &&
line.contains(ee.kind.as_slice()) &&
line.contains(ee.msg.as_slice()) {
*found_flags.get_mut(i) = true;
Expand All @@ -867,7 +877,7 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,

for (i, &flag) in found_flags.iter().enumerate() {
if !flag {
let ee = expected_errors.get(i);
let ee = &expected_errors[i];
fatal_proc_rec(format!("expected {} on line {} not found: {}",
ee.kind, ee.line, ee.msg).as_slice(),
proc_res);
Expand Down
4 changes: 2 additions & 2 deletions src/doc/complement-lang-faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ You may also be interested in browsing [GitHub's Rust][github-rust] page.

## Does it run on Windows?

Yes. All development happens in lock-step on all 3 target platforms. Using MinGW, not Cygwin. Note that the windows implementation currently has some limitations: in particular 64-bit build is [not fully supported yet][win64], and all executables created by rustc [depends on libgcc DLL at runtime][libgcc].
Yes. All development happens in lock-step on all 3 target platforms. Using MinGW, not Cygwin. Note that the windows implementation currently has some limitations: in particular 64-bit build is [not fully supported yet][win64], and all executables created by rustc [depend on libgcc DLL at runtime][libgcc].

[win64]: https://github.com/rust-lang/rust/issues/1237
[libgcc]: https://github.com/rust-lang/rust/issues/11782
Expand Down Expand Up @@ -68,7 +68,7 @@ Cleanup through RAII-style destructors is more likely to work than in catch bloc

## Why aren't modules type-parametric?

We want to maintain the option to parametrize at runtime. We may make eventually change this limitation, but initially this is how type parameters were implemented.
We want to maintain the option to parametrize at runtime. We may eventually change this limitation, but initially this is how type parameters were implemented.

## Why aren't values type-parametric? Why only items?

Expand Down
9 changes: 4 additions & 5 deletions src/doc/guide-lifetimes.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ Now we can call `compute_distance()`:
# let on_the_stack : Point = Point{x: 3.0, y: 4.0};
# let on_the_heap : Box<Point> = box Point{x: 7.0, y: 9.0};
# fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
compute_distance(&on_the_stack, on_the_heap);
compute_distance(&on_the_stack, &*on_the_heap);
~~~

Here, the `&` operator takes the address of the variable
Expand All @@ -77,10 +77,9 @@ value. We also call this _borrowing_ the local variable
`on_the_stack`, because we have created an alias: that is, another
name for the same data.

In the case of `on_the_heap`, however, no explicit action is necessary.
The compiler will automatically convert a box point to a reference like &point.
This is another form of borrowing; in this case, the contents of the owned box
are being lent out.
Likewise, in the case of `owned_box`,
the `&` operator is used in conjunction with the `*` operator
to take a reference to the contents of the box.

Whenever a caller lends data to a callee, there are some limitations on what
the caller can do with the original. For example, if the contents of a
Expand Down
2 changes: 1 addition & 1 deletion src/doc/guide-pointers.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ fn main() {
let origin = &Point { x: 0.0, y: 0.0 };
let p1 = box Point { x: 5.0, y: 3.0 };

println!("{}", compute_distance(origin, p1));
println!("{}", compute_distance(origin, &*p1));
}
~~~

Expand Down
127 changes: 127 additions & 0 deletions src/doc/guide-strings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
% The Strings Guide

Strings are an important concept to master in any programming language. If you
come from a managed language background, you may be surprised at the complexity
of string handling in a systems programming language. Efficient access and
allocation of memory for a dynamically sized structure involves a lot of
details. Luckily, Rust has lots of tools to help us here.

A **string** is a sequence of unicode scalar values encoded as a stream of
UTF-8 bytes. All strings are guaranteed to be validly-encoded UTF-8 sequences.
Additionally, strings are not null-terminated and can contain null bytes.

Rust has two main types of strings: `&str` and `String`.

# &str

The first kind is a `&str`. This is pronounced a 'string slice.' String literals
are of the type `&str`:

```{rust}
let string = "Hello there.";
```

Like any Rust type, string slices have an associated lifetime. A string literal
is a `&'static str`. A string slice can be written without an explicit
lifetime in many cases, such as in function arguments. In these cases the
lifetime will be inferred:

```{rust}
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}
```

Like vector slices, string slices are simply a pointer plus a length. This
means that they're a 'view' into an already-allocated string, such as a
`&'static str` or a `String`.

# String

A `String` is a heap-allocated string. This string is growable, and is also
guaranteed to be UTF-8.

```{rust}
let mut s = "Hello".to_string();
println!("{}", s);

s.push_str(", world.");
println!("{}", s);
```

You can coerce a `String` into a `&str` with the `as_slice()` method:

```{rust}
fn takes_slice(slice: &str) {
println!("Got: {}", slice);
}

fn main() {
let s = "Hello".to_string();
takes_slice(s.as_slice());
}
```

You can also get a `&str` from a stack-allocated array of bytes:

```{rust}
use std::str;

let x: &[u8] = &[b'a', b'b'];
let stack_str: &str = str::from_utf8(x).unwrap();
```

# Best Practices

## `String` vs. `&str`

In general, you should prefer `String` when you need ownership, and `&str` when
you just need to borrow a string. This is very similar to using `Vec<T>` vs. `&[T]`,
and `T` vs `&T` in general.

This means starting off with this:

```{rust,ignore}
fn foo(s: &str) {
```

and only moving to this:

```{rust,ignore}
fn foo(s: String) {
```

If you have good reason. It's not polite to hold on to ownership you don't
need, and it can make your lifetimes more complex. Furthermore, you can pass
either kind of string into `foo` by using `.as_slice()` on any `String` you
need to pass in, so the `&str` version is more flexible.

## Comparisons

To compare a String to a constant string, prefer `as_slice()`...

```{rust}
fn compare(string: String) {
if string.as_slice() == "Hello" {
println!("yes");
}
}
```

... over `to_string()`:

```{rust}
fn compare(string: String) {
if string == "Hello".to_string() {
println!("yes");
}
}
```

Converting a `String` to a `&str` is cheap, but converting the `&str` to a
`String` involves an allocation.

# Other Documentation

* [the `&str` API documentation](/std/str/index.html)
* [the `String` API documentation](std/string/index.html)
Loading