1
Fork 0

std: Fix all code examples

This commit is contained in:
Alex Crichton 2013-12-22 13:31:23 -08:00
parent 6c9c045064
commit 9f1739a8e1
23 changed files with 147 additions and 90 deletions

View file

@ -51,13 +51,13 @@ let my_string = "Hello, world!";
let my_c_string = my_string.to_c_str(); let my_c_string = my_string.to_c_str();
my_c_string.with_ref(|c_buffer| { my_c_string.with_ref(|c_buffer| {
unsafe { puts(c_buffer); } unsafe { puts(c_buffer); }
}) });
// Don't save off the allocation of the C string, the `c_buffer` will be // Don't save off the allocation of the C string, the `c_buffer` will be
// deallocated when this block returns! // deallocated when this block returns!
my_string.with_c_str(|c_buffer| { my_string.with_c_str(|c_buffer| {
unsafe { puts(c_buffer); } unsafe { puts(c_buffer); }
}) });
``` ```
*/ */
@ -216,7 +216,11 @@ pub trait ToCStr {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// let s = "PATH".with_c_str(|path| libc::getenv(path)) /// use std::libc;
///
/// let s = "PATH".with_c_str(|path| unsafe {
/// libc::getenv(path)
/// });
/// ``` /// ```
/// ///
/// # Failure /// # Failure

View file

@ -49,7 +49,9 @@ pub unsafe fn bump_box_refcount<T>(t: @T) { forget(t); }
* # Example * # Example
* *
* ```rust * ```rust
* let v: &[u8] = transmute("L"); * use std::cast;
*
* let v: &[u8] = unsafe { cast::transmute("L") };
* assert!(v == [76u8]); * assert!(v == [76u8]);
* ``` * ```
*/ */

View file

@ -57,7 +57,7 @@
//! //!
//! # Example //! # Example
//! //!
//! ```rust //! ```rust,should_fail
//! // Create a simple streaming channel //! // Create a simple streaming channel
//! let (port, chan) = Chan::new(); //! let (port, chan) = Chan::new();
//! do spawn { //! do spawn {
@ -81,7 +81,7 @@
//! //!
//! // The call to recv() will fail!() because the channel has already hung //! // The call to recv() will fail!() because the channel has already hung
//! // up (or been deallocated) //! // up (or been deallocated)
//! let (port, chan) = Chan::new(); //! let (port, chan) = Chan::<int>::new();
//! drop(chan); //! drop(chan);
//! port.recv(); //! port.recv();
//! ``` //! ```

View file

@ -25,7 +25,7 @@
//! //!
//! # Example //! # Example
//! //!
//! ```rust //! ```rust,notest
//! let (mut p1, c1) = Chan::new(); //! let (mut p1, c1) = Chan::new();
//! let (mut p2, c2) = Chan::new(); //! let (mut p2, c2) = Chan::new();
//! //!
@ -40,6 +40,7 @@
//! assert_eq!(val, 2); //! assert_eq!(val, 2);
//! } //! }
//! ) //! )
//! ```
#[allow(dead_code)]; #[allow(dead_code)];

View file

@ -23,13 +23,17 @@ A condition is declared through the `condition!` macro provided by the compiler:
condition! { condition! {
pub my_error: int -> ~str; pub my_error: int -> ~str;
} }
``` # fn main() {}
```
This macro declares an inner module called `my_error` with one static variable, This macro declares an inner module called `my_error` with one static variable,
`cond` that is a static `Condition` instance. To help understand what the other `cond` that is a static `Condition` instance. To help understand what the other
parameters are used for, an example usage of this condition would be: parameters are used for, an example usage of this condition would be:
```rust ```rust
# condition! { pub my_error: int -> ~str; }
# fn main() {
my_error::cond.trap(|raised_int| { my_error::cond.trap(|raised_int| {
// the condition `my_error` was raised on, and the value it raised is stored // the condition `my_error` was raised on, and the value it raised is stored
@ -51,6 +55,8 @@ my_error::cond.trap(|raised_int| {
println(my_error::cond.raise(4)); // prints "oh well" println(my_error::cond.raise(4)); // prints "oh well"
}) })
# }
``` ```
Condition handling is useful in cases where propagating errors is either to Condition handling is useful in cases where propagating errors is either to
@ -99,10 +105,12 @@ impl<T, U> Condition<T, U> {
/// ```rust /// ```rust
/// condition! { my_error: int -> int; } /// condition! { my_error: int -> int; }
/// ///
/// # fn main() {
/// let trap = my_error::cond.trap(|error| error + 3); /// let trap = my_error::cond.trap(|error| error + 3);
/// ///
/// // use `trap`'s inside method to register the handler and then run a /// // use `trap`'s inside method to register the handler and then run a
/// // block of code with the handler registered /// // block of code with the handler registered
/// # }
/// ``` /// ```
pub fn trap<'a>(&'a self, h: 'a |T| -> U) -> Trap<'a, T, U> { pub fn trap<'a>(&'a self, h: 'a |T| -> U) -> Trap<'a, T, U> {
let h: Closure = unsafe { ::cast::transmute(h) }; let h: Closure = unsafe { ::cast::transmute(h) };
@ -176,10 +184,12 @@ impl<'a, T, U> Trap<'a, T, U> {
/// ```rust /// ```rust
/// condition! { my_error: int -> int; } /// condition! { my_error: int -> int; }
/// ///
/// # fn main() {
/// let result = my_error::cond.trap(|error| error + 3).inside(|| { /// let result = my_error::cond.trap(|error| error + 3).inside(|| {
/// my_error::cond.raise(4) /// my_error::cond.raise(4)
/// }); /// });
/// assert_eq!(result, 7); /// assert_eq!(result, 7);
/// # }
/// ``` /// ```
pub fn inside<V>(&self, inner: 'a || -> V) -> V { pub fn inside<V>(&self, inner: 'a || -> V) -> V {
let _g = Guard { cond: self.cond }; let _g = Guard { cond: self.cond };

View file

@ -34,12 +34,12 @@ arguments directly while performing minimal allocations.
Some examples of the `format!` extension are: Some examples of the `format!` extension are:
```rust ```rust
format!("Hello") // => ~"Hello" format!("Hello"); // => ~"Hello"
format!("Hello, {:s}!", "world") // => ~"Hello, world!" format!("Hello, {:s}!", "world"); // => ~"Hello, world!"
format!("The number is {:d}", 1) // => ~"The number is 1" format!("The number is {:d}", 1); // => ~"The number is 1"
format!("{:?}", ~[3, 4]) // => ~"~[3, 4]" format!("{:?}", ~[3, 4]); // => ~"~[3, 4]"
format!("{value}", value=4) // => ~"4" format!("{value}", value=4); // => ~"4"
format!("{} {}", 1, 2) // => ~"1 2" format!("{} {}", 1, 2); // => ~"1 2"
``` ```
From these, you can see that the first argument is a format string. It is From these, you can see that the first argument is a format string. It is
@ -62,7 +62,7 @@ iterator over the argument. Each time a "next argument" specifier is seen, the
iterator advances. This leads to behavior like this: iterator advances. This leads to behavior like this:
```rust ```rust
format!("{1} {} {0} {}", 1, 2) // => ~"2 1 1 2" format!("{1} {} {0} {}", 1, 2); // => ~"2 1 1 2"
``` ```
The internal iterator over the argument has not been advanced by the time the The internal iterator over the argument has not been advanced by the time the
@ -89,9 +89,9 @@ identifier '=' expression
For example, the following `format!` expressions all use named argument: For example, the following `format!` expressions all use named argument:
```rust ```rust
format!("{argument}", argument = "test") // => ~"test" format!("{argument}", argument = "test"); // => ~"test"
format!("{name} {}", 1, name = 2) // => ~"2 1" format!("{name} {}", 1, name = 2); // => ~"2 1"
format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3) // => ~"a 3 ()" format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => ~"a 3 ()"
``` ```
It is illegal to put positional parameters (those without names) after arguments It is illegal to put positional parameters (those without names) after arguments
@ -160,7 +160,11 @@ When implementing a format trait for your own time, you will have to implement a
method of the signature: method of the signature:
```rust ```rust
# use std;
# struct T;
# trait SomeName<T> {
fn fmt(value: &T, f: &mut std::fmt::Formatter); fn fmt(value: &T, f: &mut std::fmt::Formatter);
# }
``` ```
Your type will be passed by-reference in `value`, and then the function should Your type will be passed by-reference in `value`, and then the function should
@ -218,7 +222,7 @@ fn main() {
There are a number of related macros in the `format!` family. The ones that are There are a number of related macros in the `format!` family. The ones that are
currently implemented are: currently implemented are:
```rust ```rust,notest
format! // described above format! // described above
write! // first argument is a &mut io::Writer, the destination write! // first argument is a &mut io::Writer, the destination
writeln! // same as write but appends a newline writeln! // same as write but appends a newline
@ -261,9 +265,13 @@ references information on the stack. Under the hood, all of
the related macros are implemented in terms of this. First the related macros are implemented in terms of this. First
off, some example usage is: off, some example usage is:
```rust ```rust,ignore
use std::fmt; use std::fmt;
# fn lol<T>() -> T { fail!() }
# let my_writer: &mut ::std::io::Writer = lol();
# let my_fn: fn(&fmt::Arguments) = lol();
format_args!(fmt::format, "this returns {}", "~str"); format_args!(fmt::format, "this returns {}", "~str");
format_args!(|args| { fmt::write(my_writer, args) }, "some {}", "args"); format_args!(|args| { fmt::write(my_writer, args) }, "some {}", "args");
format_args!(my_fn, "format {}", "string"); format_args!(my_fn, "format {}", "string");
@ -305,7 +313,7 @@ to reference the string value of the argument which was selected upon. As an
example: example:
```rust ```rust
format!("{0, select, other{#}}", "hello") // => ~"hello" format!("{0, select, other{#}}", "hello"); // => ~"hello"
``` ```
This example is the equivalent of `{0:s}` essentially. This example is the equivalent of `{0:s}` essentially.
@ -585,7 +593,9 @@ pub trait Float { fn fmt(&Self, &mut Formatter); }
/// ///
/// ```rust /// ```rust
/// use std::fmt; /// use std::fmt;
/// let w: &mut io::Writer = ...; /// use std::io;
///
/// let w = &mut io::stdout() as &mut io::Writer;
/// format_args!(|args| { fmt::write(w, args) }, "Hello, {}!", "world"); /// format_args!(|args| { fmt::write(w, args) }, "Hello, {}!", "world");
/// ``` /// ```
pub fn write(output: &mut io::Writer, args: &Arguments) { pub fn write(output: &mut io::Writer, args: &Arguments) {
@ -650,8 +660,9 @@ pub unsafe fn write_unsafe(output: &mut io::Writer,
/// ///
/// ```rust /// ```rust
/// use std::fmt; /// use std::fmt;
///
/// let s = format_args!(fmt::format, "Hello, {}!", "world"); /// let s = format_args!(fmt::format, "Hello, {}!", "world");
/// assert_eq!(s, "Hello, world!"); /// assert_eq!(s, ~"Hello, world!");
/// ``` /// ```
pub fn format(args: &Arguments) -> ~str { pub fn format(args: &Arguments) -> ~str {
unsafe { format_unsafe(args.fmt, args.args) } unsafe { format_unsafe(args.fmt, args.args) }

View file

@ -26,6 +26,9 @@ Some examples of obvious things you might want to do
* Read lines from stdin * Read lines from stdin
```rust ```rust
use std::io::buffered::BufferedReader;
use std::io::stdin;
let mut stdin = BufferedReader::new(stdin()); let mut stdin = BufferedReader::new(stdin());
for line in stdin.lines() { for line in stdin.lines() {
print(line); print(line);
@ -35,12 +38,16 @@ Some examples of obvious things you might want to do
* Read a complete file * Read a complete file
```rust ```rust
use std::io::File;
let contents = File::open(&Path::new("message.txt")).read_to_end(); let contents = File::open(&Path::new("message.txt")).read_to_end();
``` ```
* Write a line to a file * Write a line to a file
```rust ```rust
use std::io::File;
let mut file = File::create(&Path::new("message.txt")); let mut file = File::create(&Path::new("message.txt"));
file.write(bytes!("hello, file!\n")); file.write(bytes!("hello, file!\n"));
``` ```
@ -48,6 +55,9 @@ Some examples of obvious things you might want to do
* Iterate over the lines of a file * Iterate over the lines of a file
```rust ```rust
use std::io::buffered::BufferedReader;
use std::io::File;
let path = Path::new("message.txt"); let path = Path::new("message.txt");
let mut file = BufferedReader::new(File::open(&path)); let mut file = BufferedReader::new(File::open(&path));
for line in file.lines() { for line in file.lines() {
@ -58,6 +68,9 @@ Some examples of obvious things you might want to do
* Pull the lines of a file into a vector of strings * Pull the lines of a file into a vector of strings
```rust ```rust
use std::io::buffered::BufferedReader;
use std::io::File;
let path = Path::new("message.txt"); let path = Path::new("message.txt");
let mut file = BufferedReader::new(File::open(&path)); let mut file = BufferedReader::new(File::open(&path));
let lines: ~[~str] = file.lines().collect(); let lines: ~[~str] = file.lines().collect();
@ -67,7 +80,10 @@ Some examples of obvious things you might want to do
XXX This needs more improvement: TcpStream constructor taking &str, XXX This needs more improvement: TcpStream constructor taking &str,
`write_str` and `write_line` methods. `write_str` and `write_line` methods.
```rust ```rust,ignore
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
let addr = from_str::<SocketAddr>("127.0.0.1:8080").unwrap(); let addr = from_str::<SocketAddr>("127.0.0.1:8080").unwrap();
let mut socket = TcpStream::connect(addr).unwrap(); let mut socket = TcpStream::connect(addr).unwrap();
socket.write(bytes!("GET / HTTP/1.0\n\n")); socket.write(bytes!("GET / HTTP/1.0\n\n"));

View file

@ -60,11 +60,11 @@ pub enum Signum {
/// ///
/// # Example /// # Example
/// ///
/// ```rust /// ```rust,ignore
/// use std::io::signal::{Listener, Interrupt}; /// use std::io::signal::{Listener, Interrupt};
/// ///
/// let mut listener = Listener::new(); /// let mut listener = Listener::new();
/// listener.register(signal::Interrupt); /// listener.register(Interrupt);
/// ///
/// do spawn { /// do spawn {
/// loop { /// loop {

View file

@ -17,7 +17,7 @@ and create ports which will receive notifications after a period of time.
# Example # Example
```rust ```rust,ignore
use std::io::Timer; use std::io::Timer;

View file

@ -218,8 +218,8 @@ pub trait Iterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// let a = [100, 200, 300]; /// let xs = [100, 200, 300];
/// let mut it = xs.iter().map(|&x|x).peekable(); /// let mut it = xs.iter().map(|x| *x).peekable();
/// assert_eq!(it.peek().unwrap(), &100); /// assert_eq!(it.peek().unwrap(), &100);
/// assert_eq!(it.next().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 100);
/// assert_eq!(it.next().unwrap(), 200); /// assert_eq!(it.next().unwrap(), 200);
@ -338,12 +338,14 @@ pub trait Iterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::iter::count;
///
/// let xs = [2u, 3]; /// let xs = [2u, 3];
/// let ys = [0u, 1, 0, 1, 2]; /// let ys = [0u, 1, 0, 1, 2];
/// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x)); /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
/// // Check that `it` has the same elements as `ys` /// // Check that `it` has the same elements as `ys`
/// let mut i = 0; /// let mut i = 0;
/// for x: uint in it { /// for x in it {
/// assert_eq!(x, ys[i]); /// assert_eq!(x, ys[i]);
/// i += 1; /// i += 1;
/// } /// }
@ -366,7 +368,7 @@ pub trait Iterator<A> {
/// let mut sum = 0; /// let mut sum = 0;
/// for x in it { /// for x in it {
/// if x > 5 { /// if x > 5 {
/// break; /// continue;
/// } /// }
/// sum += x; /// sum += x;
/// } /// }
@ -391,14 +393,16 @@ pub trait Iterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
///let xs = [1u, 4, 2, 3, 8, 9, 6]; /// use std::iter::AdditiveIterator;
///let sum = xs.iter() ///
/// .map(|&x| x) /// let xs = [1u, 4, 2, 3, 8, 9, 6];
/// .inspect(|&x| debug!("filtering %u", x)) /// let sum = xs.iter()
/// .filter(|&x| x % 2 == 0) /// .map(|&x| x)
/// .inspect(|&x| debug!("%u made it through", x)) /// .inspect(|&x| debug!("filtering {}", x))
/// .sum(); /// .filter(|&x| x % 2 == 0)
///println(sum.to_str()); /// .inspect(|&x| debug!("{} made it through", x))
/// .sum();
/// println(sum.to_str());
/// ``` /// ```
#[inline] #[inline]
fn inspect<'r>(self, f: 'r |&A|) -> Inspect<'r, A, Self> { fn inspect<'r>(self, f: 'r |&A|) -> Inspect<'r, A, Self> {
@ -554,8 +558,8 @@ pub trait Iterator<A> {
/// ///
/// ```rust /// ```rust
/// let a = [1, 2, 3, 4, 5]; /// let a = [1, 2, 3, 4, 5];
/// assert!(a.iter().all(|&x| *x > 0)); /// assert!(a.iter().all(|x| *x > 0));
/// assert!(!a.iter().all(|&x| *x > 2)); /// assert!(!a.iter().all(|x| *x > 2));
/// ``` /// ```
#[inline] #[inline]
fn all(&mut self, f: |A| -> bool) -> bool { fn all(&mut self, f: |A| -> bool) -> bool {
@ -571,8 +575,8 @@ pub trait Iterator<A> {
/// ```rust /// ```rust
/// let a = [1, 2, 3, 4, 5]; /// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter(); /// let mut it = a.iter();
/// assert!(it.any(|&x| *x == 3)); /// assert!(it.any(|x| *x == 3));
/// assert!(!it.any(|&x| *x == 3)); /// assert!(!it.any(|x| *x == 3));
/// ``` /// ```
#[inline] #[inline]
fn any(&mut self, f: |A| -> bool) -> bool { fn any(&mut self, f: |A| -> bool) -> bool {
@ -618,7 +622,7 @@ pub trait Iterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// let xs = [-3, 0, 1, 5, -10]; /// let xs = [-3i, 0, 1, 5, -10];
/// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
/// ``` /// ```
#[inline] #[inline]
@ -642,7 +646,7 @@ pub trait Iterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// let xs = [-3, 0, 1, 5, -10]; /// let xs = [-3i, 0, 1, 5, -10];
/// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
/// ``` /// ```
#[inline] #[inline]
@ -811,6 +815,8 @@ pub trait AdditiveIterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 2, 3, 4, 5]; /// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().map(|&x| x); /// let mut it = a.iter().map(|&x| x);
/// assert!(it.sum() == 15); /// assert!(it.sum() == 15);
@ -834,7 +840,7 @@ pub trait MultiplicativeIterator<A> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::iter::count; /// use std::iter::{count, MultiplicativeIterator};
/// ///
/// fn factorial(n: uint) -> uint { /// fn factorial(n: uint) -> uint {
/// count(1u, 1).take_while(|&i| i <= n).product() /// count(1u, 1).take_while(|&i| i <= n).product()
@ -907,6 +913,8 @@ pub trait ClonableIterator {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::iter::{ClonableIterator, count};
///
/// let a = count(1,1).take(1); /// let a = count(1,1).take(1);
/// let mut cy = a.cycle(); /// let mut cy = a.cycle();
/// assert_eq!(cy.next(), Some(1)); /// assert_eq!(cy.next(), Some(1));

View file

@ -29,10 +29,10 @@ local_data_key!(key_int: int)
local_data_key!(key_vector: ~[int]) local_data_key!(key_vector: ~[int])
local_data::set(key_int, 3); local_data::set(key_int, 3);
local_data::get(key_int, |opt| assert_eq!(opt, Some(&3))); local_data::get(key_int, |opt| assert_eq!(opt.map(|x| *x), Some(3)));
local_data::set(key_vector, ~[4]); local_data::set(key_vector, ~[4]);
local_data::get(key_vector, |opt| assert_eq!(opt, Some(&~[4]))); local_data::get(key_vector, |opt| assert_eq!(*opt.unwrap(), ~[4]));
``` ```
*/ */

View file

@ -78,7 +78,7 @@ error,hello=warn // turn on global error logging and also warn for hello
Each of these macros will expand to code similar to: Each of these macros will expand to code similar to:
```rust ```rust,notest
if log_level <= my_module_log_level() { if log_level <= my_module_log_level() {
::std::logging::log(log_level, format!(...)); ::std::logging::log(log_level, format!(...));
} }

View file

@ -339,7 +339,8 @@ impl Round for f32 {
/// The fractional part of the number, satisfying: /// The fractional part of the number, satisfying:
/// ///
/// ```rust /// ```rust
/// assert!(x == trunc(x) + fract(x)) /// let x = 1.65f32;
/// assert!(x == x.trunc() + x.fract())
/// ``` /// ```
/// ///
#[inline] #[inline]

View file

@ -357,7 +357,8 @@ impl Round for f64 {
/// The fractional part of the number, satisfying: /// The fractional part of the number, satisfying:
/// ///
/// ```rust /// ```rust
/// assert!(x == trunc(x) + fract(x)) /// let x = 1.65f64;
/// assert!(x == x.trunc() + x.fract())
/// ``` /// ```
/// ///
#[inline] #[inline]

View file

@ -101,8 +101,7 @@ pub trait Unsigned: Num {}
/// Times trait /// Times trait
/// ///
/// ```rust /// ```rust
/// use num::Times; /// let ten = 10u;
/// let ten = 10 as uint;
/// let mut accum = 0; /// let mut accum = 0;
/// ten.times(|| { accum += 1; }) /// ten.times(|| { accum += 1; })
/// ``` /// ```
@ -176,10 +175,10 @@ pub trait Round {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// assert_approx_eq!(1.3f32.round(), 1.0); /// assert_approx_eq!(1.3f32.trunc(), 1.0);
/// assert_approx_eq!((-1.3f32).round(), -1.0); /// assert_approx_eq!((-1.3f32).trunc(), -1.0);
/// assert_approx_eq!(1.5f32.round(), 1.0); /// assert_approx_eq!(1.5f32.trunc(), 1.0);
/// assert_approx_eq!((-1.5f32).round(), -1.0); /// assert_approx_eq!((-1.5f32).trunc(), -1.0);
/// ``` /// ```
fn trunc(&self) -> Self; fn trunc(&self) -> Self;
@ -188,10 +187,10 @@ pub trait Round {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// assert_approx_eq!(1.3f32.round(), 0.3); /// assert_approx_eq!(1.3f32.fract(), 0.3);
/// assert_approx_eq!((-1.3f32).round(), -0.3); /// assert_approx_eq!((-1.3f32).fract(), -0.3);
/// assert_approx_eq!(1.5f32.round(), 0.5); /// assert_approx_eq!(1.5f32.fract(), 0.5);
/// assert_approx_eq!((-1.5f32).round(), -0.5); /// assert_approx_eq!((-1.5f32).fract(), -0.5);
/// ``` /// ```
fn fract(&self) -> Self; fn fract(&self) -> Self;
} }
@ -225,7 +224,9 @@ pub trait Algebraic {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// let sixteen: float = num::pow(2.0, 4.0); /// use std::num;
///
/// let sixteen: f64 = num::pow(2.0, 4.0);
/// assert_eq!(sixteen, 16.0); /// assert_eq!(sixteen, 16.0);
/// ``` /// ```
#[inline(always)] pub fn pow<T: Algebraic>(value: T, n: T) -> T { value.pow(&n) } #[inline(always)] pub fn pow<T: Algebraic>(value: T, n: T) -> T { value.pow(&n) }
@ -266,6 +267,8 @@ pub trait Trigonometric {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::f32;
///
/// let y = 3f32.sqrt(); /// let y = 3f32.sqrt();
/// let x = 1f32; /// let x = 1f32;
/// assert_approx_eq!(y.atan2(&x), f32::consts::PI / 3f32); /// assert_approx_eq!(y.atan2(&x), f32::consts::PI / 3f32);

View file

@ -54,12 +54,11 @@ actually operates on the path; it is only intended for display.
```rust ```rust
let mut path = Path::new("/tmp/path"); let mut path = Path::new("/tmp/path");
debug!("path: {}", path.display()); println!("path: {}", path.display());
path.set_filename("foo"); path.set_filename("foo");
path.push("bar"); path.push("bar");
debug!("new path: {}", path.display()); println!("new path: {}", path.display());
let b = std::os::path_exists(&path); println!("path exists: {}", path.exists());
debug!("path exists: {}", b);
``` ```
*/ */

View file

@ -39,7 +39,7 @@ use num;
/// ///
/// fn main() { /// fn main() {
/// let gamma = Gamma::new(2.0, 5.0); /// let gamma = Gamma::new(2.0, 5.0);
/// let v = gamma.ind_sample(rand::task_rng()); /// let v = gamma.ind_sample(&mut rand::task_rng());
/// println!("{} is from a Gamma(2, 5) distribution", v); /// println!("{} is from a Gamma(2, 5) distribution", v);
/// } /// }
/// ``` /// ```

View file

@ -98,10 +98,10 @@ pub struct Weighted<T> {
/// let wc = WeightedChoice::new(~[Weighted { weight: 2, item: 'a' }, /// let wc = WeightedChoice::new(~[Weighted { weight: 2, item: 'a' },
/// Weighted { weight: 4, item: 'b' }, /// Weighted { weight: 4, item: 'b' },
/// Weighted { weight: 1, item: 'c' }]); /// Weighted { weight: 1, item: 'c' }]);
/// let rng = rand::task_rng(); /// let mut rng = rand::task_rng();
/// for _ in range(0, 16) { /// for _ in range(0, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice. /// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
/// println!("{}", wc.ind_sample(rng)); /// println!("{}", wc.ind_sample(&mut rng));
/// } /// }
/// } /// }
/// ``` /// ```

View file

@ -123,7 +123,7 @@ impl IndependentSample<f64> for Normal {
/// fn main() { /// fn main() {
/// // mean 2, standard deviation 3 /// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0); /// let log_normal = LogNormal::new(2.0, 3.0);
/// let v = normal.ind_sample(&mut rand::task_rng()); /// let v = log_normal.ind_sample(&mut rand::task_rng());
/// println!("{} is from an ln N(2, 9) distribution", v) /// println!("{} is from an ln N(2, 9) distribution", v)
/// } /// }
/// ``` /// ```

View file

@ -39,10 +39,10 @@ use rand::distributions::{Sample, IndependentSample};
/// ///
/// fn main() { /// fn main() {
/// let between = Range::new(10u, 10000u); /// let between = Range::new(10u, 10000u);
/// let rng = rand::task_rng(); /// let mut rng = rand::task_rng();
/// let mut sum = 0; /// let mut sum = 0;
/// for _ in range(0, 1000) { /// for _ in range(0, 1000) {
/// sum += between.ind_sample(rng); /// sum += between.ind_sample(&mut rng);
/// } /// }
/// println!("{}", sum); /// println!("{}", sum);
/// } /// }

View file

@ -64,7 +64,7 @@ use std::rand;
fn main () { fn main () {
let tuple_ptr = rand::random::<~(f64, char)>(); let tuple_ptr = rand::random::<~(f64, char)>();
println!(tuple_ptr) println!("{:?}", tuple_ptr)
} }
``` ```
*/ */
@ -227,7 +227,7 @@ pub trait Rng {
/// let mut rng = rand::task_rng(); /// let mut rng = rand::task_rng();
/// let n: uint = rng.gen_range(0u, 10); /// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n); /// println!("{}", n);
/// let m: float = rng.gen_range(-40.0, 1.3e5); /// let m: f64 = rng.gen_range(-40.0, 1.3e5);
/// println!("{}", m); /// println!("{}", m);
/// } /// }
/// ``` /// ```
@ -292,8 +292,10 @@ pub trait Rng {
/// use std::rand::Rng; /// use std::rand::Rng;
/// ///
/// fn main() { /// fn main() {
/// println!("{:?}", rand::task_rng().choose_option([1,2,4,8,16,32])); /// let choices = [1, 2, 4, 8, 16, 32];
/// println!("{:?}", rand::task_rng().choose_option([])); /// let mut rng = rand::task_rng();
/// println!("{:?}", rng.choose_option(choices));
/// println!("{:?}", rng.choose_option(choices.slice_to(0)));
/// } /// }
/// ``` /// ```
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
@ -388,11 +390,10 @@ pub trait SeedableRng<Seed>: Rng {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::rand; /// use std::rand::{Rng, SeedableRng, StdRng};
/// use std::rand::Rng;
/// ///
/// fn main() { /// fn main() {
/// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]); /// let mut rng: StdRng = SeedableRng::from_seed(&[1, 2, 3, 4]);
/// println!("{}", rng.gen::<f64>()); /// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]); /// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>()); /// println!("{}", rng.gen::<f64>());

View file

@ -1458,10 +1458,10 @@ pub trait StrSlice<'a> {
/// let v: ~[(uint, uint)] = "abcXXXabcYYYabc".match_indices("abc").collect(); /// let v: ~[(uint, uint)] = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, ~[(0,3), (6,9), (12,15)]); /// assert_eq!(v, ~[(0,3), (6,9), (12,15)]);
/// ///
/// let v: ~[(uint, uint)] = "1abcabc2".split_str("abc").collect(); /// let v: ~[(uint, uint)] = "1abcabc2".match_indices("abc").collect();
/// assert_eq!(v, ~[(1,4), (4,7)]); /// assert_eq!(v, ~[(1,4), (4,7)]);
/// ///
/// let v: ~[(uint, uint)] = "ababa".split_str("aba").collect(); /// let v: ~[(uint, uint)] = "ababa".match_indices("aba").collect();
/// assert_eq!(v, ~[(0, 3)]); // only the first `aba` /// assert_eq!(v, ~[(0, 3)]); // only the first `aba`
/// ``` /// ```
fn match_indices(&self, sep: &'a str) -> MatchesIndexIterator<'a>; fn match_indices(&self, sep: &'a str) -> MatchesIndexIterator<'a>;
@ -1536,7 +1536,7 @@ pub trait StrSlice<'a> {
/// assert!(" \t\n".is_whitespace()); /// assert!(" \t\n".is_whitespace());
/// assert!("".is_whitespace()); /// assert!("".is_whitespace());
/// ///
/// assert!( !"abc.is_whitespace()); /// assert!( !"abc".is_whitespace());
/// ``` /// ```
fn is_whitespace(&self) -> bool; fn is_whitespace(&self) -> bool;
@ -1606,7 +1606,7 @@ pub trait StrSlice<'a> {
/// let s = "Löwe 老虎 Léopard"; /// let s = "Löwe 老虎 Léopard";
/// assert_eq!(s.slice(0, 1), "L"); /// assert_eq!(s.slice(0, 1), "L");
/// ///
/// assert_eq!(s.slice(1, 9), "öwe 老")); /// assert_eq!(s.slice(1, 9), "öwe 老");
/// ///
/// // these will fail: /// // these will fail:
/// // byte 2 lies within `ö`: /// // byte 2 lies within `ö`:
@ -1808,6 +1808,8 @@ pub trait StrSlice<'a> {
/// `.char_indices`. /// `.char_indices`.
/// ///
/// ```rust /// ```rust
/// use std::str::CharRange;
///
/// let s = "中华Việt Nam"; /// let s = "中华Việt Nam";
/// let mut i = 0u; /// let mut i = 0u;
/// while i < s.len() { /// while i < s.len() {
@ -1949,11 +1951,11 @@ pub trait StrSlice<'a> {
/// ///
/// ```rust /// ```rust
/// let s = "Löwe 老虎 Léopard"; /// let s = "Löwe 老虎 Léopard";
/// let (c, s1) = s.shift_slice_char(); /// let (c, s1) = s.slice_shift_char();
/// assert_eq!(c, 'L'); /// assert_eq!(c, 'L');
/// assert_eq!(s1, "öwe 老虎 Léopard"); /// assert_eq!(s1, "öwe 老虎 Léopard");
/// ///
/// let (c, s2) = s1.shift_slice_char(); /// let (c, s2) = s1.slice_shift_char();
/// assert_eq!(c, 'ö'); /// assert_eq!(c, 'ö');
/// assert_eq!(s2, "we 老虎 Léopard"); /// assert_eq!(s2, "we 老虎 Léopard");
/// ``` /// ```

View file

@ -2174,12 +2174,12 @@ pub trait MutableVector<'a, T> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// let mut v = [5, 4, 1, 3, 2]; /// let mut v = [5i, 4, 1, 3, 2];
/// v.sort(|a, b| a.cmp(b)); /// v.sort_by(|a, b| a.cmp(b));
/// assert_eq!(v, [1, 2, 3, 4, 5]); /// assert_eq!(v, [1, 2, 3, 4, 5]);
/// ///
/// // reverse sorting /// // reverse sorting
/// v.sort(|a, b| b.cmp(a)); /// v.sort_by(|a, b| b.cmp(a));
/// assert_eq!(v, [5, 4, 3, 2, 1]); /// assert_eq!(v, [5, 4, 3, 2, 1]);
/// ``` /// ```
fn sort_by(self, compare: |&T, &T| -> Ordering); fn sort_by(self, compare: |&T, &T| -> Ordering);
@ -2395,8 +2395,6 @@ pub trait MutableTotalOrdVector<T> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use std::vec;
///
/// let mut v = [-5, 4, 1, -3, 2]; /// let mut v = [-5, 4, 1, -3, 2];
/// ///
/// v.sort(); /// v.sort();