error
import std::core::error; · source
Every standard library error implements Error: it prints a message for a person through Display, a fuller form for a developer through Debug, and may name the error it was caused by. ErrorReport is the one owning carrier any error converts into, so a function that can fail in several unrelated ways can return them all as one type.
Types
Error
type trait Error : Display, Debug {
source(&this) -> Option<virtual &Error>;
}
source is the error this one was caused by, if it keeps one; the default answers None. A wrapper error — one that adds context to a lower-level failure — overrides it to hand the inner error out as a trait object, so a reader can walk the whole chain.
Methods
source(&this) -> Option<virtual &Error>;
source(&this) -> Option<virtual &Error>;The error this one was caused by, if it keeps one. None by default.
Implementors
implement trait Error for struct DecodeError
std::encoding::error
implement trait Error for struct TomlError
std::encoding::toml::error
implement trait Error for struct YamlError
std::encoding::yaml::error
implement trait Error for struct ArgumentError
std::env::arguments
implement trait Error for struct IoError
std::fmt::display
implement trait Error for struct Utf8Error
std::fmt::display
implement trait Error for struct JsonError
std::fmt::display
implement trait Error for struct ValueDecodeError
std::fmt::display
implement<E> trait Error for enum FromTextError<E> where E: Error
std::fmt::display
implement trait Error for enum RandomError
std::fmt::display
implement trait Error for struct AllocationError
std::fmt::display
implement trait Error for struct ConversionError
std::fmt::display
implement trait Error for enum FormatError
std::fmt::display
implement trait Error for enum JoinError
std::future::executor
implement trait Error for struct LogSpecificationError
std::log::logger
implement trait Error for enum UrlError
std::net::address::url
implement<T> trait Error for struct SendError<T>
std::sync::channel
implement<T> trait Error for enum TrySendError<T>
std::sync::channel
implement trait Error for enum ReceiveError
std::sync::channel
implement trait Error for enum TryReceiveError
std::sync::channel
implement trait Error for enum ReceiveTimeoutError
std::sync::channel
implement trait Error for enum TestError
std::test::error
implement trait Error for enum SpawnError
std::thread
implement trait Error for struct DateTimeError
std::time::datetime
ErrorReport
type struct ErrorReport {
private message: String;
private causes: Array<String>;
}
An error kept as text: its own message and the message of each error in its chain of sources, outermost first. Keeping the text rather than the error is what lets a report outlive the error it came from, and what lets errors of different types travel as one. Display prints the message and the causes joined by : ; Debug puts each cause on a line of its own, after caused by: .
Any Error converts into a report through From, so ? in a function returning Result<T, ErrorReport> passes on whatever error it meets:
import std::core::error::{ ErrorReport };
import std::collections::string::{ String };
import std::fs::{ File, Path };
function settings(path: Path) -> Result<String, ErrorReport> {
const text: String = File::read_text(path)?;
return Result::Ok(text);
}
A report is not an Error itself, which is what keeps its From impl and the identity From<T> for T from both applying to one type.
Constructors
static from_error<E>(error: &E) -> ErrorReport where E: Error;
static from_error<E>(error: &E) -> ErrorReport where E: Error;The report of error: its Display text and that of each source.
Methods
message(&this) -> Str;
message(&this) -> Str;The error's own message.
causes(&this) -> implement Iterator<Str>;
causes(&this) -> implement Iterator<Str>;The message of each error in the chain of sources, outermost first.
Trait implementations
implement<E> trait From<E> for struct ErrorReport where E: Error
implement trait Display for struct ErrorReport
implement trait Debug for struct ErrorReport
BoxedError
type struct BoxedError {
private value: mut u8*;
private object: virtual &Error;
}
Any error, owned whole: the value of whatever type implements Error, moved to the heap and reached through its Error table. Any Error converts into one (BoxedError::new, or From), so ? in a function returning Result<T, BoxedError> passes on errors of any type, and the caller still holds each error itself, its source chain included, where ErrorReport keeps only text. It prints as the error does.
Constructors
static new<E>(error: E) -> BoxedError where E: Error;
static new<E>(error: E) -> BoxedError where E: Error;error, moved into a carrier of its own.
Methods
error(&this) -> virtual &Error;
error(&this) -> virtual &Error;The error carried, through its Error table: its source chain, and its Display and Debug text.
Trait implementations
implement<E> trait From<E> for struct BoxedError where E: Error
implement trait Drop for struct BoxedError
implement trait Display for struct BoxedError
implement trait Debug for struct BoxedError
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
type trait Error : Display, Debug {
source(&this) -> Option<virtual &Error>;
}An error: a message for a person through Display, a fuller form through Debug, and the error it was caused by, if it keeps one.
type trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.
type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.
Error::source(&this) -> Option<virtual &Error>The error this one was caused by, if it keeps one. None by default.
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
virtual &Trait
virtual mut &Trait
virtual Trait*Makes a trait object: a value of any type implementing the trait, held with a table of that type's methods for it, so code taking one is compiled once for every implementing type. The three forms borrow the value, borrow it mutably, or point at it. Written on anything but a trait it is refused (E0316); written on a method, it is E0117.
language referencetype trait Error : Display, Debug {
source(&this) -> Option<virtual &Error>;
}An error: a message for a person through Display, a fuller form through Debug, and the error it was caused by, if it keeps one.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct ErrorReport {}An error kept as text: its own message and the message of each error in its chain of sources, outermost first. Any Error makes one (from_error). It prints its message and its causes joined by : , and through Debug each cause on a line of its own.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
ErrorReport.message: Stringtype struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
ErrorReport.causes: Array<String>type struct Array<T, A = GlobalAllocator> where A: Allocator {}A growable sequence of Ts stored contiguously, owning its elements; A is the allocator its storage comes from. Indexing out of range panics; get answers None instead.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::core::error;The common error trait, and one owning carrier any error converts into.
module pagetype struct ErrorReport {}An error kept as text: its own message and the message of each error in its chain of sources, outermost first. Any Error makes one (from_error). It prints its message and its causes joined by : , and through Debug each cause on a line of its own.
type struct File {}An open file, closed when the value is released. It implements Read and Write; the static methods read or write a whole file in one call.
type struct Path {}A borrowed filesystem path: a view of text owned elsewhere, valid while that text is. A string literal or a Str converts to one where a Path is wanted; PathBuf is the owned form join builds.
function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function settings(path: Path) -> Result<String, ErrorReport>(parameter) path: Pathtype enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
const name: Type = value;An immutable binding: it cannot be reassigned after initialisation. The annotation may be omitted when an initialiser is present - the binding takes the initialiser's concrete type, inferred locally. Mutability is opt-in through mut.
const text: Stringstatic File::read_text(path: Path) -> Result<String, IoError>The whole of the file at path as text. Fails with InvalidData if the bytes are not UTF-8; every failure names path.
(parameter) path: Pathvalue?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. It works on any type implementing Try, in a function whose return type implements FromResidual of it; an error of another type converts through From.
return value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
Result::Ok(T)const text: Stringtype struct BoxedError {}Any error, owned whole: the value of whatever type implements Error, moved to the heap and reached through its Error table.
BoxedError.value: mut u8*mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
BoxedError.object: virtual &ErrorError::source(&this) -> Option<virtual &Error>The error this one was caused by, if it keeps one. None by default.
std::core::errorOption::Noneimplement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referenceimplement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype struct DecodeError with [Eq, Debug] {
position: i64;
kind: DecodeErrorKind;
}A decoding failure: its kind, and the byte offset in the input text at which the decoder found it.
std::encoding::errortype struct TomlError {
kind: TomlErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why TOML text could not be read or a value written, and where: the failure's kind, its position in the source (0 for the writer's), and a message for a person to read.
std::encoding::toml::errortype struct YamlError {
kind: YamlErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why YAML text could not be read, and where: the failure's kind, its position in the source, and a message for a person to read.
std::encoding::yaml::errortype struct ArgumentError with [Eq, Clone, Debug] {
kind: ArgumentErrorKind;
argument: String;
}The argument a command line went wrong at, and how.
std::env::argumentstype struct IoError {
kind: IoErrorKind;
os_code: i32;
}The error of a failed I/O operation: its kind, the operating system's own code, and, when the operation named one, what it was doing and the path. It prints as could not open config.toml: not found.
type struct Utf8Error {
valid_up_to: i64;
error_length: Option<i64>;
}Where a byte sequence stops being UTF-8; see Str::from_utf8.
type struct JsonError {
kind: JsonErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why JSON text could not be parsed, and where: the failure's kind, its position in the source, and a message for a person to read.
std::encoding::json::errortype struct ValueDecodeError {}Why a Value could not be read as a type: where in it (path, from the value read: .servers[2].port, empty for the value itself), what was expected there and what was found. It prints as at .servers[2].port: expected a u16, found a string.
type parameter Ewhere E: Error
type enum Name {
Unit,
Payload(T),
Named { x: i32 },
}An algebraic data type. Variants may be bare or carry a tuple or struct payload, and a match on an enum must cover every variant. Name::Variant names a variant; methods are added with implement enum Name { ... }.
type enum FromTextError<E> {
Parse(E);
Decode(ValueDecodeError);
}Why text could not be read as a type: it is not the format's text (Parse, holding the format's own error - a JsonError, YamlError or TomlError), or the value it holds is not the type (Decode).
where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type enum RandomError with [Eq] {
EntropyUnavailable;
EmptyRange;
InvalidWeights;
}What went wrong in a fallible random operation.
std::random::errortype struct AllocationError {
kind: AllocationErrorKind;
layout: Layout;
}The error an Allocator returns: what went wrong (kind) and the layout that was requested when it did (layout; for a reallocate, the new layout).
type struct ConversionError {}What went wrong in a TryFrom / TryInto. Carries a short static message describing the failure; richer diagnostics are a caller concern.
type enum FormatError {
Io(IoError);
Allocation(AllocationError);
}Why formatting a value failed: the sink refused the bytes, or a sink that grows (a String) could not.
type enum JoinError {
Cancelled;
Panicked(PanicInfo);
}Why a join did not yield a value.
type struct LogSpecificationError with [Eq, Clone, Debug] {
entry: String;
}A logging specification entry Logging::configure could not read.
type enum UrlError with [Eq, Clone, Debug] {
MissingScheme;
EmptyScheme;
EmptyHost;
InvalidPort;
}Why a URL failed to parse.
std::net::address::urltype parameter Ttype struct SendError<T> {
value: T;
}Error returned by Sender::send when the receiver has been dropped. Carries the value back so the caller does not lose it.
type enum TrySendError<T> {
Full(T);
Disconnected(T);
}Why Sender::try_send did not queue its value. Each variant carries the value back so the caller does not lose it.
type enum ReceiveError with [Eq, Clone, Debug] {
Disconnected;
}Error returned by a blocking Receiver::receive.
type enum TryReceiveError with [Eq, Clone, Debug] {
Empty;
Disconnected;
}Error returned by the non-blocking Receiver::try_receive.
type enum ReceiveTimeoutError with [Eq, Clone, Debug] {
Timeout;
Disconnected;
}Why Receiver::receive_timeout returned no value.
type enum TestError {
Failed(String);
Other(String);
}Why a test failed. The runner prints the variant's message verbatim to stderr from the child process before exiting non-zero, so the parent can show the failing message in the test summary.
std::test::errortype enum SpawnError with [Eq, Clone, Debug] {
OutOfMemory;
PermissionDenied;
ResourceLimit;
Other;
}Why a spawn failed.
std::threadtype struct DateTimeError with [Eq, Debug] {
position: i64;
kind: DateTimeErrorKind;
}A parse failure: its kind and the byte offset in the text where it was found - the offending byte, or the start of the out-of-range field.
std::time::datetimetype trait From<T> {
static from(value: T) -> This;
}A conversion that always succeeds, from a T into this type.
for (mut i: i32 = 0; i < n; i++) { ... }
for (item in iterable) { ... }
for ((i, item) in items.iterate().enumerate()) { ... }Two forms. The C-style for (init; condition; step) scopes its loop variable to the body. for (x in expr) iterates an Iterator, a range such as 0..n, or an Iterable, which it consumes: an Array, a Slice of Copy elements, or a fixed-size array. A loop that only borrows writes its borrowing iterator, xs.iter() or xs.iterate_references(). The binding may be a tuple pattern that takes each item apart, nested and with _ elements: enumerate() yields (index, element) with an i64 index, and zip yields (a, b). A loop variable the body never reads is warned about (W0001); write _.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static ErrorReport::from_error<E>(error: &E) -> ErrorReport
where E: ErrorThe report of error: its Display text and that of each source.
const E: f64 = 2.718281828459045;(parameter) error: &EBoxedError::error(&this) -> virtual &ErrorThe error carried, through its Error table: its source chain, and its Display and Debug text.
type struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
ErrorReport::causes(&this) -> implement Iterator<Str>The message of each error in the chain of sources, outermost first.
std::core::error-> implement Trait<T>An opaque type: some one concrete type that implements the trait, without naming it. The compiler infers the real type and uses it everywhere; callers see only the trait's methods. How the stdlib returns iterators without exposing their engines.
language referencetype trait Iterator {
type Item;
next(mut &this) -> Option<This::Item>;
count(mut &this) -> i64;
fold<Acc, F>(mut &this, initial: Acc, f: F) -> Acc
where F: (Acc, This::Item) -> Acc;
for_each<F>(mut &this, f: F) -> void
where F: (This::Item) -> void;
take(this, n: i64) -> implement Iterator<This::Item>;
skip(this, n: i64) -> implement Iterator<This::Item>;
map<B, F>(this, f: F) -> implement Iterator<B>
where F: (This::Item) -> B;
filter<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
chain<J>(this, other: J) -> implement Iterator<This::Item>
where J: Iterator<This::Item>;
enumerate(this) -> implement Iterator<(i64, This::Item)>;
zip<J>(this, other: J) -> implement Iterator<(This::Item, J::Item)>
where J: Iterator;
collect<C>(this) -> C
where C: FromIterator<This::Item>;
sum<S>(this) -> S
where S: Sum, This: Iterator<S>;
reverse(this) -> implement Iterator<This::Item>
where This: DoubleEndedIterator;
peekable(this) -> implement Peekable<This::Item>;
flat_map<B, F>(this, f: F) -> implement Iterator<B::Item>
where F: (This::Item) -> B, B: Iterator;
flatten(this) -> implement Iterator<This::Item::Item>
where This::Item: Iterator;
take_while<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
skip_while<P>(this, pred: P) -> implement Iterator<This::Item>
where P: (&This::Item) -> boolean;
step_by(this, step: i64) -> implement Iterator<This::Item>;
filter_map<B, F>(this, f: F) -> implement Iterator<B>
where F: (This::Item) -> Option<B>;
any<P>(mut &this, pred: P) -> boolean
where P: (This::Item) -> boolean;
all<P>(mut &this, pred: P) -> boolean
where P: (This::Item) -> boolean;
find<P>(mut &this, pred: P) -> Option<This::Item>
where P: (&This::Item) -> boolean;
min(mut &this) -> Option<This::Item>
where This::Item: Ord;
max(mut &this) -> Option<This::Item>
where This::Item: Ord;
min_by<F>(mut &this, compare: F) -> Option<This::Item>
where F: (&This::Item, &This::Item) -> Ordering;
max_by<F>(mut &this, compare: F) -> Option<This::Item>
where F: (&This::Item, &This::Item) -> Ordering;
min_by_key<K, F>(mut &this, key: F) -> Option<This::Item>
where F: (&This::Item) -> K, K: Ord;
max_by_key<K, F>(mut &this, key: F) -> Option<This::Item>
where F: (&This::Item) -> K, K: Ord;
last(mut &this) -> Option<This::Item>;
nth(mut &this, n: i64) -> Option<This::Item>;
position<P>(mut &this, pred: P) -> Option<i64>
where P: (This::Item) -> boolean;
product<S>(this) -> S
where S: Product, This: Iterator<S>;
}A source of values handed out one at a time by next, until it returns None. for (x in source) drives one, and the adapter methods below build new iterators from it:
type struct BoxedError {}Any error, owned whole: the value of whatever type implements Error, moved to the heap and reached through its Error table.
static BoxedError::new<E>(error: E) -> BoxedError
where E: Errorerror, moved into a carrier of its own.
new T { field: value }
new Path(args)
new E::Variant
new T[n]Heap allocation. new T { .. } places a struct literal on the heap and yields a T*, and new E::V does the same for a unit variant. new Path(args) places the value a call returns, whatever its type: new Table::new(8), new Option<i64>::Some(41), new make_pair(3, 4). new T[n] reserves n uninitialised T - the typed malloc. The storage comes from the value type's Allocate implementation, or else the global allocator. A type is not a function, so new Point(1, 2) is refused (E0231).
(parameter) error: Etype trait Drop {
drop(mut &this) -> void;
}A type that releases something when a value of it ends: memory, a file handle, a lock. The compiler calls drop once when an owned value goes out of scope; release a value early with mem::drop(value).