channel
import std::sync::channel; · source
Multi-producer, single-consumer channels. Channel::unbounded::<T>() and Channel::bounded::<T>(capacity) open a channel and return both of its ends together, its Sender<T> first. Each Sender<T> is independently owned and movable into its own thread, and is cloned for more producers. Values of any type — including owned data like String — move through the FIFO queue.
import std::core::pair::{ Pair };
import std::sync::channel::{ Channel, Receiver, Sender };
import std::thread;
const { first: tx, second: rx }: Pair<Sender<i32>, Receiver<i32>> = Channel::unbounded::<i32>();
// move `tx` into a worker thread; keep `rx` here
const h = thread::spawn(move () -> i32 {
tx.send(42);
return 0; // `tx` is released with the closure as the thread ends
});
match (rx.receive()) {
Result::Ok(v) => { /* v is 42 */ }
Result::Err(_) => { }
}
h.join().unwrap();
Types
Channel
type struct Channel {}
An unbounded channel queues every value sent. A bounded one holds at most capacity values (at least 1): send on a full channel blocks until the receiver takes one, or returns the value in Err(SendError) if the receiver is dropped meanwhile.
Static functions
static unbounded<T>() -> Pair<Sender<T>, Receiver<T>>;
static unbounded<T>() -> Pair<Sender<T>, Receiver<T>>;A channel that queues every value sent.
static bounded<T>(capacity: i64) -> Pair<Sender<T>, Receiver<T>>;
static bounded<T>(capacity: i64) -> Pair<Sender<T>, Receiver<T>>;A channel holding at most capacity values: send on a full one waits for the receiver to take a value. Panics when capacity is less than 1.
Sender<T>
type struct Sender<T> {
private inner: mut ChannelInner<T>*;
}
send moves a value into the queue, waiting for room on a full bounded channel. try_send never waits: on a full channel it hands the value back in Err(TrySendError::Full). clone() mints another producer; close() consumes the sender and is equivalent to dropping it early.
Methods
send(&this, value: T) -> Result<(), SendError<T>>;
send(&this, value: T) -> Result<(), SendError<T>>;Enqueue value, first waiting for room when a bounded channel is full. Returns Err(SendError{value}) if the receiver has been dropped (the value is handed back unconsumed).
try_send(&this, value: T) -> Result<(), TrySendError<T>>;
try_send(&this, value: T) -> Result<(), TrySendError<T>>;Enqueue value without waiting. Returns Err(Full(value)) when a bounded channel already holds its capacity (or no memory could be had for the value), Err(Disconnected(value)) when the receiver has been dropped; either hands the value back unconsumed.
clone(&this) -> Sender<T>;
clone(&this) -> Sender<T>;Create another sender on the same channel (multi-producer).
close(mut this) -> void;
close(mut this) -> void;Explicitly drop this sender now (rather than at scope end). Useful after moving a sender into a thread body, where the value must be released before the body returns.
Receiver<T>
type struct Receiver<T> {
private inner: mut ChannelInner<T>*;
}
receive() blocks; receive_timeout(duration) gives up with Err(Timeout) when the time runs out; try_receive() returns Err(Empty) immediately when nothing is queued. The receiver is not cloneable — there is one consumer.
A Receiver<T> is an Iterator<T>: for (value in rx) takes each value as it arrives and ends once every sender has dropped and the queue is drained.
import std::core::pair::{ Pair };
import std::sync::channel::{ Channel, Receiver, Sender };
import std::thread;
const { first: jobs, second: results }: Pair<Sender<i32>, Receiver<i32>> = Channel::bounded::<i32>(2);
const producer = thread::spawn(move () -> i32 {
mut i: i32 = 0;
while (i < 5) {
jobs.send(i);
i = i + 1;
}
return 0;
});
mut sum: i32 = 0;
for (value in results) {
sum = sum + value;
}
producer.join().unwrap();
Methods
receive(&this) -> Result<T, ReceiveError>;
receive(&this) -> Result<T, ReceiveError>;Block until a value is available and return it, or return Err(Disconnected) once every sender has dropped and the queue is drained.
receive_timeout(&this, duration: Duration) -> Result<T, ReceiveTimeoutError>;
receive_timeout(&this, duration: Duration) -> Result<T, ReceiveTimeoutError>;Wait no longer than duration for a value and return it. Err(Timeout) when the time runs out first, Err(Disconnected) once every sender has dropped and the queue is drained.
try_receive(&this) -> Result<T, TryReceiveError>;
try_receive(&this) -> Result<T, TryReceiveError>;Non-blocking receive. Returns Err(Empty) if no value is ready but senders remain, Err(Disconnected) if the channel is drained and all senders have dropped.
The errors
type struct SendError<T> {
value: T;
}
type enum TrySendError<T> {
Full(T);
Disconnected(T);
}
type enum ReceiveError with [Eq, Clone, Debug] {
Disconnected;
}
type enum TryReceiveError with [Eq, Clone, Debug] {
Empty;
Disconnected;
}
type enum ReceiveTimeoutError with [Eq, Clone, Debug] {
Timeout;
Disconnected;
}
SendError
Properties
| Property | Type |
|---|---|
value | T |
TrySendError
Variants
| Variant | Notes |
|---|---|
Full(T) | The channel already holds as many values as it can, or no memory could be had for one more. |
Disconnected(T) | The receiver has been dropped. |
ReceiveError
Variants
| Variant |
|---|
Disconnected |
TryReceiveError
Variants
| Variant |
|---|
Empty |
Disconnected |
ReceiveTimeoutError
Variants
| Variant | Notes |
|---|---|
Timeout | The time ran out with no value sent and a sender still alive. |
Disconnected | Every sender has dropped and the queue is empty. |
Disconnection
When every Sender has been dropped, a blocked receive() returns Err(ReceiveError::Disconnected) and try_receive() returns Err(TryReceiveError::Disconnected). A disconnected channel stays disconnected: a sender is made only with the channel or by cloning a live one.
When the Receiver is dropped, send() returns Err(SendError) and try_send() Err(TrySendError::Disconnected), each handing the value back, rather than queueing into a channel nobody will drain.
Underneath, a heap inner holds a Mutex over the channel's state — a raw singly-linked node queue with its length, plus a live-sender count and a total-handle refcount — a ConditionVariable the receiver waits on, and one a sender waits on for room. The inner is reclaimed when the last handle of either kind drops. Values move out of dequeued nodes through raw pointers, so the move-checker sees each as a clean transfer — no aliasing, no double free.
Trait implementations
Sender
implement<T> trait Drop for struct Sender<T>
Receiver
implement<T> trait Drop for struct Receiver<T>
implement<T> trait Iterator<T> for struct Receiver<T>
SendError
implement<T> trait Display for struct SendError<T>
implement<T> trait Debug for struct SendError<T>
implement<T> trait Error for struct SendError<T>
TrySendError
implement<T> trait Display for enum TrySendError<T>
implement<T> trait Debug for enum TrySendError<T>
implement<T> trait Error for enum TrySendError<T>
ReceiveError
implement trait Display for enum ReceiveError
implement trait Error for enum ReceiveError
TryReceiveError
implement trait Display for enum TryReceiveError
implement trait Error for enum TryReceiveError
ReceiveTimeoutError
implement trait Display for enum ReceiveTimeoutError
implement trait Error for enum ReceiveTimeoutError
Receiver::drop drains and drops whatever is still queued.
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).
type struct Pair<A, B> with [Eq, Clone] {
first: A;
second: B;
}Two values held together, first and second: a map's key with its value.
namespace std::sync::channel;std::sync::channel: multi-producer, single-consumer channels.
module pagetype struct Channel {}Opens channels. A channel's two ends come out together, its Sender<T> first; more senders are clones of that one:
type struct Receiver<T> {}The receiving half of a channel. Not cloneable (single consumer).
std::sync::channeltype struct Sender<T> {}The sending half of a channel. Cloneable for multiple producers.
std::sync::channelconst 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.
static Channel::unbounded<T>() -> Pair<Sender<T>, Receiver<T>>A channel that queues every value sent.
std::sync::channelconst NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const h: JoinHandle<T>function spawn<F, T>(body: F) -> JoinHandle<T>
where F: () -> T + Send, T: SendSpawn a thread that runs body() and returns a handle to its T result. body is moved into the new thread: a move closure, a non-capturing lambda or a named function. Panics on allocation or thread-creation failure; use try_spawn for a fallible spawn.
move (params) -> Ret { body }Prefixes a lambda that captures its environment by move: captured outer bindings are consumed where the lambda is built and released by a synthesised Drop at scope exit. Capturing a non-Copy value already gives a lambda move semantics; move states it explicitly.
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.
match (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, constants, and tuple and destructuring patterns, such as (0, 1..8) or Option::Some((count, _)), and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
type 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.
Result::Ok(T)vpattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
Result::Err(E)const h: JoinHandle<T>JoinHandle::join(mut this) -> Result<T, PanicInfo>Block until the thread finishes. Returns Ok with the body's result, or Err with the panic that ended the body, which the thread reported when it panicked. The PanicInfo's message is this thread's copy, valid until this thread joins another panicked thread: copy it to keep it.
Result::unwrap(this) -> TThe Ok value, aborting on Err. Consumes the result: the value moves out to the caller and the error, if any, is released.
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 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 Channel {}Opens channels. A channel's two ends come out together, its Sender<T> first; more senders are clones of that one:
type struct Sender<T> {}The sending half of a channel. Cloneable for multiple producers.
type parameter Tprivate 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.
Sender.inner: mut ChannelInner<T>*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.
type parameter Ttype struct Receiver<T> {}The receiving half of a channel. Not cloneable (single consumer).
Receiver.inner: mut ChannelInner<T>*type parameter Tstatic Channel::bounded<T>(capacity: i64) -> Pair<Sender<T>, Receiver<T>>A channel holding at most capacity values: send on a full one waits for the receiver to take a value. Panics when capacity is less than 1.
const producer: JoinHandle<T>mut i: i32while (condition) { ... }Repeats its body while the condition holds. The condition is checked before every iteration, so the body may run zero times.
language referencemut i: i32mut sum: i32for (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 _.
valuefor (item in iterable) { ... }Separates the loop variable from the sequence in a for loop. The sequence is evaluated once; the loop lowers to loop { match (it.next()) { Some(x) => .., None => break } }.
mut sum: i32const producer: JoinHandle<T>type 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.
SendError.value: Ttype parameter Ttype 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 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.
TrySendError::Full(T)The channel already holds as many values as it can, or no memory could be had for one more.
type parameter TTrySendError::Disconnected(T)The receiver has been dropped.
type enum ReceiveError with [Eq, Clone, Debug] {
Disconnected;
}Error returned by a blocking Receiver::receive.
type struct Point with [Eq, Clone, Debug] { .. }Asks the compiler to generate implementations of the listed traits for the type, each working through its fields or variants in declaration order. The derivable traits are Eq, Ord, Hash, Clone, Debug, Default, ToValue and FromValue, and the text formats' FromJson, ToJson, FromYaml, ToYaml, FromToml and ToToml. The clause comes after the name and its parameters, before where.
type trait Eq<Rhs = This> {
equals(&this, other: &Rhs) -> boolean;
}Types that support value equality with a value of Rhs, which is the type itself unless an implementation names another: implement trait Eq for Str compares two Strs, and implement trait Eq<string> for Str a Str with a string.
type trait Clone {
clone(&this) -> This;
}A type whose values can be duplicated into independent copies. A type takes it with with [Clone] on its declaration, or by implementing clone by hand.
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.
ReceiveError::Disconnectedtype enum TryReceiveError with [Eq, Clone, Debug] {
Empty;
Disconnected;
}Error returned by the non-blocking Receiver::try_receive.
TryReceiveError::EmptyTryReceiveError::Disconnectedtype enum ReceiveTimeoutError with [Eq, Clone, Debug] {
Timeout;
Disconnected;
}Why Receiver::receive_timeout returned no value.
ReceiveTimeoutError::TimeoutThe time ran out with no value sent and a sender still alive.
ReceiveTimeoutError::DisconnectedEvery sender has dropped and the queue is empty.
type 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.
Sender::send(&this, value: T) -> Result<(), SendError<T>>Enqueue value, first waiting for room when a bounded channel is full. Returns Err(SendError{value}) if the receiver has been dropped (the value is handed back unconsumed).
type 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.
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.
(parameter) capacity: i64Sender::try_send(&this, value: T) -> Result<(), TrySendError<T>>Enqueue value without waiting. Returns Err(Full(value)) when a bounded channel already holds its capacity (or no memory could be had for the value), Err(Disconnected(value)) when the receiver has been dropped; either hands the value back unconsumed.
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.
TrySendError::Full(T)The channel already holds as many values as it can, or no memory could be had for one more.
std::sync::channelSender::clone(&this) -> Sender<T>Create another sender on the same channel (multi-producer).
std::sync::channelSender::close(mut this) -> voidExplicitly drop this sender now (rather than at scope end). Useful after moving a sender into a thread body, where the value must be released before the body returns.
std::sync::channel&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.
(parameter) value: Tprimitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
SendError.value: Tmut thisA by-value receiver the body may also reassign. The receiver is moved into the method and consumed; the caller's value may not be used afterwards.
language referenceReceiver::receive(&this) -> Result<T, ReceiveError>Block until a value is available and return it, or return Err(Disconnected) once every sender has dropped and the queue is drained.
Receiver::receive_timeout(&this, duration: Duration) -> Result<T, ReceiveTimeoutError>Wait no longer than duration for a value and return it. Err(Timeout) when the time runs out first, Err(Disconnected) once every sender has dropped and the queue is drained.
ReceiveTimeoutError::TimeoutThe time ran out with no value sent and a sender still alive.
std::sync::channelReceiver::try_receive(&this) -> Result<T, TryReceiveError>Non-blocking receive. Returns Err(Empty) if no value is ready but senders remain, Err(Disconnected) if the channel is drained and all senders have dropped.
TryReceiveError::Emptytype 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 enum ReceiveError with [Eq, Clone, Debug] {
Disconnected;
}Error returned by a blocking Receiver::receive.
(parameter) duration: Durationtype struct Duration with [Eq, Ord, Debug] {
const NANOSECONDS_PER_SECOND: u64 = 1000000000;
const NANOSECONDS_PER_MILLISECOND: u64 = 1000000;
const NANOSECONDS_PER_MICROSECOND: u64 = 1000;
const MILLISECONDS_PER_SECOND: u64 = 1000;
const MICROSECONDS_PER_SECOND: u64 = 1000000;
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 3600;
const SECONDS_PER_DAY: u64 = 86400;
}A length of time: whole secs plus a sub-second nanos remainder (0 <= nanos < 1_000_000_000). POD; copy-by-value, no drop. Ordered by seconds, then nanoseconds.
type enum ReceiveTimeoutError with [Eq, Clone, Debug] {
Timeout;
Disconnected;
}Why Receiver::receive_timeout returned no value.
type enum TryReceiveError with [Eq, Clone, Debug] {
Empty;
Disconnected;
}Error returned by the non-blocking Receiver::try_receive.
ReceiveError::DisconnectedTryReceiveError::Disconnectedtype struct Mutex<T, A = GlobalAllocator> where A: Allocator {}A value of type T that one thread at a time may use. lock waits for the lock and returns a MutexGuard through which the value is read and written; dropping the guard releases the lock. The lock and the value live in one block allocated from A, so the Mutex handle can move while the lock stays put.
type struct ConditionVariable {}A condition variable: lets a thread holding a Mutex give up the lock and sleep until another thread calls notify_one or notify_all. A pthread_cond_t on unix; on Windows a CONDITION_VARIABLE waited on with the mutex's SRW lock. Wakes can be spurious, so wait in a loop that re-checks the condition.
implement 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.
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 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).
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype 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 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.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language reference