array
import std::collections::array; — in the prelude · source
Types
Array<T, A>
type struct Array<T, A = GlobalAlloc> where A: Allocator {
ptr: T*;
length: i64;
capacity: i64;
alloc: A;
static new() -> Array<T, GlobalAlloc>;
static new_in(alloc: A) -> Array<T, A>;
static with_capacity(capacity: u64) -> Array<T, GlobalAlloc>;
static with_capacity_in(capacity: u64, alloc: A) -> Array<T, A>;
static try_with_capacity_in(capacity: u64, alloc: A) -> Result<Array<T, A>, AllocError>;
length(&this) -> i64;
capacity(&this) -> i64;
is_empty(&this) -> boolean;
get(&this, index: u64) -> Option<T>
where T: Copy;
get_ref(&this, index: u64) -> Option<T*>;
as_ptr(&this) -> T*;
as_slice(&this) -> Slice<T>;
iter(&this) -> implement Iterator<T>
where T: Copy;
iter_ref(&this) -> implement Iterator<T*>;
push(mut &this, value: T) -> void;
try_push(mut &this, value: T) -> Result<(), AllocError>;
pop(mut &this) -> Option<T>;
set(mut &this, index: u64, value: T) -> void;
swap_remove(mut &this, index: u64) -> T;
first(&this) -> Option<T*>;
last(&this) -> Option<T*>;
index_of(&this, value: &T) -> Option<u64>
where T: Eq;
contains(&this, value: &T) -> boolean
where T: Eq;
reverse(mut &this) -> void;
insert(mut &this, index: u64, value: T) -> void;
remove(mut &this, index: u64) -> T;
truncate(mut &this, new_length: u64) -> void;
clear(mut &this) -> void;
sort(mut &this) -> void
where T: Ord;
sort_by(mut &this, less: (&T, &T) -> boolean) -> void;
append(mut &this, source: Slice<T>) -> void
where T: Copy;
try_append(mut &this, source: Slice<T>) -> Result<(), AllocError>
where T: Copy;
resize(mut &this, new_length: u64, value: T) -> void
where T: Copy;
try_resize(mut &this, new_length: u64, value: T) -> Result<(), AllocError>
where T: Copy;
reserve(mut &this, additional: u64) -> Result<(), AllocError>;
reserve_exact(mut &this, additional: u64) -> Result<(), AllocError>;
shrink_to_fit(mut &this) -> void;
resize_storage(mut &this, new_capacity: i64) -> Result<(), AllocError>;
}
A growable, heap-backed, contiguous sequence. [T] is a spelling of Array<T>, which is why it is in the prelude. Push and pop at the end are amortized O(1); indexed access is O(1). Growth doubles capacity, starting at 4. The first three fields are laid out to match the [T] fat pointer the compiler emits, so a field declared [string] and an Array::<string>::new() agree on every byte offset.
Algorithms that do not need ownership should take a Slice<T> — call as_slice() at the boundary and write the algorithm once.
mut names: Array<String> = Array::<String>::new();
names.push(String::from("ada"));
names.push(String::from("grace"));
for (n in names.iter_ref()) {
println(f"{*n}");
}
Properties
| Property | Type |
|---|---|
ptr | T* |
length | i64 |
capacity | i64 |
alloc | A |
Constructors
static new() -> Array<T, GlobalAlloc>;
static new() -> Array<T, GlobalAlloc>;Empty array backed by GlobalAlloc.
static new_in(alloc: A) -> Array<T, A>;
static new_in(alloc: A) -> Array<T, A>;Empty array with a caller-supplied allocator.
static with_capacity(capacity: u64) -> Array<T, GlobalAlloc>;
static with_capacity(capacity: u64) -> Array<T, GlobalAlloc>;Preallocate room for capacity elements. Panics on allocation failure; use try_with_capacity_in to recover.
static with_capacity_in(capacity: u64, alloc: A) -> Array<T, A>;
static try_with_capacity_in(capacity: u64, alloc: A) -> Result<Array<T, A>, AllocError>;
Methods
length(&this) -> i64;
capacity(&this) -> i64;
is_empty(&this) -> boolean;
get(&this, index: u64) -> Option<T> where T: Copy;
get(&this, index: u64) -> Option<T> where T: Copy;Bounds-checked read by value. Gated on T: Copy: the result is an independent bitwise duplicate while the array retains ownership of the stored element, so handing back a copy is only sound when T carries no Drop obligation. For owning T, borrow in place with get_ref (or move an element out with swap_remove/pop).
get_ref(&this, index: u64) -> Option<T*>;
get_ref(&this, index: u64) -> Option<T*>;Bounds-checked borrow. Returns a pointer to the element in place; the array keeps ownership, so this is sound for every T (Copy or owning). The pointer is invalidated by any reallocating method (push, reserve, shrink_to_fit).
as_ptr(&this) -> T*;
as_ptr(&this) -> T*;Raw pointer. Invalidated by any method that may reallocate (push, reserve, shrink_to_fit).
as_slice(&this) -> Slice<T>;
as_slice(&this) -> Slice<T>;Borrow the initialized prefix. Slice is invalidated by any reallocating method.
iter(&this) -> implement Iterator<T> where T: Copy;
iter(&this) -> implement Iterator<T> where T: Copy;Iterate over the elements in order, yielding each by value (bitwise copy). Gated on T: Copy for the same reason as get: a yielded owning value would alias storage the array still owns. For owning T, walk by index with length() + get_ref. The iterator is invalidated by any reallocating method on the array (push, reserve, shrink_to_fit).
iter_ref(&this) -> implement Iterator<T*>;
iter_ref(&this) -> implement Iterator<T*>;Iterate by shared borrow, yielding T* for each element in order. Unlike iter, this is sound for every T (Copy or owning) because it hands out borrows, never copies. The pointers are invalidated by any reallocating method (push, reserve, insert, shrink_to_fit). This is the way to walk an Array<String> / Array<Box<...>> without cloning.
push(mut &this, value: T) -> void;
try_push(mut &this, value: T) -> Result<(), AllocError>;
pop(mut &this) -> Option<T>;
set(mut &this, index: u64, value: T) -> void;
set(mut &this, index: u64, value: T) -> void;Overwrite the element at index, taking ownership of value. The previous occupant is released in place before the slot is reused: a raw slot store (this.ptr[index] = value) does NOT drop the destination, so for owning T (String, Box<T>, ...) the old element's resources would otherwise leak. Panics on out-of-range.
swap_remove(mut &this, index: u64) -> T;
swap_remove(mut &this, index: u64) -> T;Remove at index by swapping in the last element. O(1) but doesn't preserve order. Panics on out-of-range.
first(&this) -> Option<T*>;
first(&this) -> Option<T*>;First element by shared borrow, or None if empty. Sound for every T (the array keeps ownership). Invalidated by any reallocating method.
last(&this) -> Option<T*>;
last(&this) -> Option<T*>;Last element by shared borrow, or None if empty.
index_of(&this, value: &T) -> Option<u64> where T: Eq;
index_of(&this, value: &T) -> Option<u64> where T: Eq;Index of the first element equal to value, or None. Linear scan; T: Eq.
contains(&this, value: &T) -> boolean where T: Eq;
contains(&this, value: &T) -> boolean where T: Eq;True if some element equals value. T: Eq.
reverse(mut &this) -> void;
reverse(mut &this) -> void;Reverse the elements in place. Sound for owning T: each pair is exchanged with a three-step move (identical to mem::swap's body, inlined here so the method stays self-contained - see note below).
insert(mut &this, index: u64, value: T) -> void;
insert(mut &this, index: u64, value: T) -> void;Insert value at index, shifting later elements right by one. index == length appends. Panics if index > length. Panics on allocation failure; use the Result-returning forms for recovery via try_push if you need fallibility on the common (append) path.
remove(mut &this, index: u64) -> T;
remove(mut &this, index: u64) -> T;Remove and return the element at index, shifting later elements left by one to preserve order (O(n)). Panics if out of range. For O(1) removal when order doesn't matter, use swap_remove.
truncate(mut &this, new_length: u64) -> void;
truncate(mut &this, new_length: u64) -> void;Shorten to at most new_length, releasing the truncated elements in place. A no-op if new_length >= length. Keeps capacity.
clear(mut &this) -> void;
clear(mut &this) -> void;Release every initialized element (the [0, length) prefix) in place, then reset the length to zero while keeping the backing capacity. Mirrors drop's element teardown so Array<String>, Array<Box<...>>, and similar owning shapes don't leak their contents. Follow with shrink_to_fit to release the capacity, or drop when the array itself goes away.
sort(mut &this) -> void where T: Ord;
sort(mut &this) -> void where T: Ord;Sort the array in place, ascending, by T::compare.
sort_by(mut &this, less: (&T, &T) -> boolean) -> void;
sort_by(mut &this, less: (&T, &T) -> boolean) -> void;Sort in place using a user-supplied "less-than" predicate. Returns no value; mutates the array. Same complexity and stability as sort(). The predicate must impose a strict weak ordering (irreflexive, transitive, with the implied equivalence being transitive) or the result is unspecified.
append(mut &this, source: Slice<T>) -> void where T: Copy;
append(mut &this, source: Slice<T>) -> void where T: Copy;Append every element of source to the end of this array. Panics on allocation failure; use try_append to recover.
try_append(mut &this, source: Slice<T>) -> Result<(), AllocError> where T: Copy;
try_append(mut &this, source: Slice<T>) -> Result<(), AllocError> where T: Copy;Fallible bulk append. Reserves space for all elements first so partial copies are impossible; either all elements are appended or none are. Gated on T: Copy (see append): the append is a bitwise memcpy out of the borrowed source.
resize(mut &this, new_length: u64, value: T) -> void where T: Copy;
resize(mut &this, new_length: u64, value: T) -> void where T: Copy;Set the length to exactly new_length, filling any new slots with value. Shrinking drops the elements above new_length, exactly as truncate does; growing leaves every slot initialized, so the whole [0, new_length) range is readable afterwards.
try_resize(mut &this, new_length: u64, value: T) -> Result<(), AllocError> where T: Copy;
try_resize(mut &this, new_length: u64, value: T) -> Result<(), AllocError> where T: Copy;Fallible resize. Reserves the whole growth up front, so the array is either resized or left exactly as it was - never partially grown.
reserve(mut &this, additional: u64) -> Result<(), AllocError>;
reserve_exact(mut &this, additional: u64) -> Result<(), AllocError>;
shrink_to_fit(mut &this) -> void;
resize_storage(mut &this, new_capacity: i64) -> Result<(), AllocError>;
Constructing
new and with_capacity are backed by GlobalAlloc; the _in forms take your allocator. with_capacity panics on allocation failure — try_with_capacity_in is the recoverable form. To build an array from an iterator, use the free function from_iter.
Reading
getis a bounds-checked read by value and needsT: Copy;get_refis the bounds-checked borrow and is sound for everyT.first/lastborrow, and returnNonewhen empty.index_ofandcontainsare linear scans overT: Eq.
Every pointer, slice, and iterator handed out here is invalidated by any method that may reallocate — push, insert, reserve, shrink_to_fit.
Iterating
iter()(whereT: Copy) yields each element by value.iter_ref()yieldsT*and is sound for everyT. This is how you walk anArray<String>orArray<Box<...>>without cloning.iter_ref().copied()(whereT: Copy) anditer_ref().cloned()(whereT: Clone) turn the borrowing cursor back into a by-value one.
Modifying
push appends and pop takes from the end; try_push returns Result<(), AllocError> instead of panicking, as do reserve and reserve_exact. insert and remove shift the tail and preserve order; swap_remove is the O(1) alternative when order does not matter. set, truncate, clear, and resize all drop whatever they displace, so an Array<String> never leaks through them. clear and truncate keep the capacity — follow with shrink_to_fit to release it.
resize is how you build a fixed-size read buffer. An array only exposes [0, length), so with_capacity alone leaves nothing to read into.
Sorting
sort() (where T: Ord) sorts ascending in place using a hybrid in-place quicksort: median-of-three pivot above a cutoff of 16 elements, insertion sort below it. O(n log n) average, no allocation. Two caveats: it is not stable, and the worst case is O(n²) — v1.0 has no introsort fallback. Owning elements are moved with mem::swap, so the drop obligation stays intact.
sort_by(less) takes your own strict-weak-ordering predicate. It must be a function pointer; non-capturing lambdas convert implicitly, and a capturing closure in method position is rejected (E0458) in v1.0. Capture by indirection, or pull the sort into a free function.
Trait implementations
implement<T, A> trait Drop for struct Array<T, A> where T: Drop, A: Allocator
implement<T> trait Clone for struct Array<T, GlobalAlloc> where T: Clone
implement<T> trait Default for struct Array<T, GlobalAlloc>
implement<T, A> trait Eq for struct Array<T, A> where T: Eq, A: Allocator
implement<T, A> trait Hash for struct Array<T, A> where T: Hash, A: Allocator
implement<T, A> trait Index<i8, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<i16, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<i32, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<i64, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<isize, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<u8, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<u16, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<u32, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<u64, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Index<usize, T> for struct Array<T, A> where A: Allocator
implement<T, A> trait Display for struct Array<T, A> where T: Display, A: Allocator
std::fmt::display
implement<T, A> trait Debug for struct Array<T, A> where T: Debug, A: Allocator
std::fmt::display
Clone is a deep copy into a fresh buffer sized to length. Default is a fresh empty array that allocates nothing. Eq is equal length and equal elements in order. Hash folds the length first, so [1, 2] and [1, 2, 0] differ. Display renders [a, b, c] and Debug the same with each element in Debug form; both live in fmt.
Free Functions
function from_iter<I, T>(it: I) -> Array<T> where I: Iterator<T>;
function from_iter<I, T>(it: I) -> Array<T> where I: Iterator<T>;Collect every element an iterator yields into a fresh Array<T>, in order. it is consumed. T is recovered from the iterator's Iterator<T> impl, and the result element type is fixed by the expected type at the call site:
mut squares: Array<i32> = from_iter((0..10).map(square));
It is a free function rather than an Iterator::collect default for a specific reason: a non-self-returning trait default gets cloned into every Iterator impl, including the by-reference cursor over Array<T> — whose clone would instantiate Array<T>, then Array<T*>, then Array<T**>, diverging until it ran out of memory. As a free function only concrete call sites instantiate it.
Constants
const INITIAL_CAPACITY: i64 = 4;
const SORT_INSERTION_CUTOFF: u64 = 16;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 Array<T, A = GlobalAlloc> where A: Allocator {
ptr: T*;
length: i64;
capacity: i64;
alloc: A;
}Array<T, A>: growable, heap-backed, contiguous sequence.
type parameter Ttype parameter Awhere A: Allocator
type struct GlobalAlloc {}Zero-sized handle to the process-wide allocator. Construct with GlobalAlloc::new(); all instances dispatch through the same underlying backend.
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 trait Allocator {
allocate(mut &this, layout: Layout) -> Result<NonNull<u8>, AllocError>;
deallocate(mut &this, ptr: NonNull<u8>, layout: Layout) -> void;
reallocate(mut &this, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<u8>, AllocError>;
}Allocator: the trait every heap strategy implements.
std::alloc::allocatorArray.ptr: T*type parameter TArray.length: i64Array.capacity: i64Array.alloc: Astatic 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 Array::new() -> Array<T, GlobalAlloc>Empty array backed by GlobalAlloc.
type struct Array<T, A = GlobalAlloc> where A: Allocator {
ptr: T*;
length: i64;
capacity: i64;
alloc: A;
}Array<T, A>: growable, heap-backed, contiguous sequence.
std::collections::arraystatic Array::new_in(alloc: A) -> Array<T, A>Empty array with a caller-supplied allocator.
(parameter) alloc: Astatic Array::with_capacity(capacity: u64) -> Array<T, GlobalAlloc>Preallocate room for capacity elements. Panics on allocation failure; use try_with_capacity_in to recover.
(parameter) capacity: u64static Array::with_capacity_in(capacity: u64, alloc: A) -> Array<T, A>static Array::try_with_capacity_in(capacity: u64, alloc: A) -> Result<Array<T, A>, AllocError>type struct AllocError {
kind: AllocErrorKind;
layout: Layout;
}&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.
Array::is_empty(&this) -> booleanArray::get(&this, index: u64) -> Option<T>
where T: CopyBounds-checked read by value. Gated on T: Copy: the result is an independent bitwise duplicate while the array retains ownership of the stored element, so handing back a copy is only sound when T carries no Drop obligation.
(parameter) index: u64type trait Copy {}Types whose values can be duplicated by a bitwise copy. Integers, floats, pointers, and pure-POD structs qualify; anything that owns resources (heap storage, file handles, refcount) does not.
std::core::markerArray::get_ref(&this, index: u64) -> Option<T*>Bounds-checked borrow. Returns a pointer to the element in place; the array keeps ownership, so this is sound for every T (Copy or owning). The pointer is invalidated by any reallocating method (push, reserve, shrink_to_fit).
Array::as_ptr(&this) -> T*Raw pointer. Invalidated by any method that may reallocate (push, reserve, shrink_to_fit).
Array::as_slice(&this) -> Slice<T>Borrow the initialized prefix. Slice is invalidated by any reallocating method.
type struct Slice<T> {
ptr: T*;
length: u64;
}Slice<T>: a borrowed view into a contiguous sequence.
std::core::sliceArray::iter(&this) -> implement Iterator<T>
where T: CopyIterate over the elements in order, yielding each by value (bitwise copy). Gated on T: Copy for the same reason as get: a yielded owning value would alias storage the array still owns. For owning T, walk by index with length() + get_ref.
-> 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) -> u64;
fold<Acc>(mut &this, initial: Acc, f: (Acc, This::Item) -> Acc) -> Acc;
for_each(mut &this, f: (This::Item) -> void) -> void;
take(this, n: u64) -> TakeIter<This>;
skip(this, n: u64) -> SkipIter<This>;
map<B>(this, f: (This::Item) -> B) -> MapIter<This, B>;
filter(this, pred: (&This::Item) -> boolean) -> FilterIter<This>;
chain<J>(this, other: J) -> ChainIter<This, J>;
// … 7 more
}Array::iter_ref(&this) -> implement Iterator<T*>Iterate by shared borrow, yielding T* for each element in order. Unlike iter, this is sound for every T (Copy or owning) because it hands out borrows, never copies. The pointers are invalidated by any reallocating method (push, reserve, insert, shrink_to_fit).
Array::push(mut &this, value: T) -> voidmut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
(parameter) value: TArray::try_push(mut &this, value: T) -> Result<(), AllocError>primitive ()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.
Array::pop(mut &this) -> Option<T>Array::set(mut &this, index: u64, value: T) -> voidOverwrite the element at index, taking ownership of value. The previous occupant is released in place before the slot is reused: a raw slot store (this.ptr[index] = value) does NOT drop the destination, so for owning T (String, Box<T>, ...) the old element's resources would otherwise leak.
Array::swap_remove(mut &this, index: u64) -> TRemove at index by swapping in the last element. O(1) but doesn't preserve order. Panics on out-of-range.
Array::first(&this) -> Option<T*>First element by shared borrow, or None if empty. Sound for every T (the array keeps ownership). Invalidated by any reallocating method.
Array::last(&this) -> Option<T*>Last element by shared borrow, or None if empty.
Array::index_of(&this, value: &T) -> Option<u64>
where T: EqIndex of the first element equal to value, or None. Linear scan; T: Eq.
(parameter) value: &Ttype trait Eq {
equals(&this, other: &This) -> boolean;
}Types that support value equality. equals(a, b) must be reflexive, symmetric, and transitive.
Array::contains(&this, value: &T) -> boolean
where T: EqTrue if some element equals value. T: Eq.
Array::reverse(mut &this) -> voidReverse the elements in place. Sound for owning T: each pair is exchanged with a three-step move (identical to mem::swap's body, inlined here so the method stays self-contained - see note below).
Array::insert(mut &this, index: u64, value: T) -> voidInsert value at index, shifting later elements right by one. index == length appends. Panics if index > length. Panics on allocation failure; use the Result-returning forms for recovery via try_push if you need fallibility on the common (append) path.
Array::remove(mut &this, index: u64) -> TRemove and return the element at index, shifting later elements left by one to preserve order (O(n)). Panics if out of range. For O(1) removal when order doesn't matter, use swap_remove.
Array::truncate(mut &this, new_length: u64) -> voidShorten to at most new_length, releasing the truncated elements in place. A no-op if new_length >= length. Keeps capacity.
(parameter) new_length: u64Array::clear(mut &this) -> voidRelease every initialized element (the [0, length) prefix) in place, then reset the length to zero while keeping the backing capacity. Mirrors drop's element teardown so Array<String>, Array<Box<...>>, and similar owning shapes don't leak their contents.
Array::sort(mut &this) -> void
where T: OrdSort the array in place, ascending, by T::compare.
type trait Ord : Eq {
compare(&this, other: &This) -> Ordering;
}Types that have a total order: every pair is Less, Equal, or Greater. compare must be consistent with equals: if a.equals(b) then a.compare(b) == Equal.
Array::sort_by(mut &this, less: (&T, &T) -> boolean) -> voidSort in place using a user-supplied "less-than" predicate. Returns no value; mutates the array. Same complexity and stability as sort(). The predicate must impose a strict weak ordering (irreflexive, transitive, with the implied equivalence being transitive) or the result is unspecified.
(parameter) less: (&T, &T) -> booleanArray::append(mut &this, source: Slice<T>) -> void
where T: CopyAppend every element of source to the end of this array. Panics on allocation failure; use try_append to recover.
(parameter) source: Slice<T>Array::try_append(mut &this, source: Slice<T>) -> Result<(), AllocError>
where T: CopyFallible bulk append. Reserves space for all elements first so partial copies are impossible; either all elements are appended or none are. Gated on T: Copy (see append): the append is a bitwise memcpy out of the borrowed source.
Array::resize(mut &this, new_length: u64, value: T) -> void
where T: CopySet the length to exactly new_length, filling any new slots with value. Shrinking drops the elements above new_length, exactly as truncate does; growing leaves every slot initialized, so the whole [0, new_length) range is readable afterwards.
Array::try_resize(mut &this, new_length: u64, value: T) -> Result<(), AllocError>
where T: CopyFallible resize. Reserves the whole growth up front, so the array is either resized or left exactly as it was - never partially grown.
Array::reserve(mut &this, additional: u64) -> Result<(), AllocError>(parameter) additional: u64Array::reserve_exact(mut &this, additional: u64) -> Result<(), AllocError>Array::shrink_to_fit(mut &this) -> voidArray::resize_storage(mut &this, new_capacity: i64) -> Result<(), AllocError>(parameter) new_capacity: i64mut 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.
mut names: Array<String>type struct String<A = GlobalAlloc> {
buffer: RawBuffer<u8, A>;
length: u64;
}String: owned, heap-allocated, length-typed UTF-8.
std::collections::stringstatic Array::new() -> Array<T, GlobalAlloc>Empty array backed by GlobalAlloc.
mut names: Array<String>Array::push(mut &this, value: T) -> voidstatic String::from<T>(item: T) -> StringCreate a String from item, using the SAME compile-time static match (T) dispatch as push - the central T-generic constructor. String::from("hi"), String::from(65 as u32), String::from(true), String::from(some_str) all route through push. Panics on allocation failure.
for (mut i: i32 = 0; i < n; i++) { ... }
for (item in iterable) { ... }Two forms. The C-style for (init; condition; step) scopes its loop variable to the body. for (x in expr) iterates anything with next() -> Option<T>: an iterator, a range such as 0..n, an Array or Slice (their iter() is inserted for you), or a fixed-size array.
n: String*for (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 } }.
Array::iter_ref(&this) -> implement Iterator<T*>Iterate by shared borrow, yielding T* for each element in order. Unlike iter, this is sound for every T (Copy or owning) because it hands out borrows, never copies. The pointers are invalidated by any reallocating method (push, reserve, insert, shrink_to_fit).
n: String*mut squares: Array<i32>function from_iter<I, T>(it: I) -> Array<T>
where I: Iterator<T>Collect every element an iterator yields into a fresh Array<T>, in order. it is consumed. T is recovered from the iterator's Iterator<T> impl, and the result element type is fixed by the expected type at the call site:
start..endA half-open range - start up to but excluding end - and sugar for Range::new(start, end): an iterator usable in for, and an ordinary value anywhere else. It binds looser than arithmetic, so a..b + 1 is a..(b + 1).
const 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 INITIAL_CAPACITY: i64 = 4;const SORT_INSERTION_CUTOFF: u64 = 16;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::collections::array;Array<T, A>: growable, heap-backed, contiguous sequence.
module pageprimitive stringNUL-terminated raw string (u8*), matching the C ABI. Length-typed text is Str / String.
Array::as_slice(&this) -> Slice<T>Borrow the initialized prefix. Slice is invalidated by any reallocating method.
std::collections::arrayArray.ptr: T*Array.length: i64Array.capacity: i64Array.alloc: Astatic Array::new_in(alloc: A) -> Array<T, A>Empty array with a caller-supplied allocator.
std::collections::arraystatic Array::with_capacity(capacity: u64) -> Array<T, GlobalAlloc>Preallocate room for capacity elements. Panics on allocation failure; use try_with_capacity_in to recover.
static Array::try_with_capacity_in(capacity: u64, alloc: A) -> Result<Array<T, A>, AllocError>static Array::with_capacity_in(capacity: u64, alloc: A) -> Array<T, A>Array::is_empty(&this) -> booleanArray::get(&this, index: u64) -> Option<T>
where T: CopyBounds-checked read by value. Gated on T: Copy: the result is an independent bitwise duplicate while the array retains ownership of the stored element, so handing back a copy is only sound when T carries no Drop obligation.
Array::get_ref(&this, index: u64) -> Option<T*>Bounds-checked borrow. Returns a pointer to the element in place; the array keeps ownership, so this is sound for every T (Copy or owning). The pointer is invalidated by any reallocating method (push, reserve, shrink_to_fit).
Array::swap_remove(mut &this, index: u64) -> TRemove at index by swapping in the last element. O(1) but doesn't preserve order. Panics on out-of-range.
Array::pop(mut &this) -> Option<T>Array::reserve(mut &this, additional: u64) -> Result<(), AllocError>Array::shrink_to_fit(mut &this) -> voidArray::as_ptr(&this) -> T*Raw pointer. Invalidated by any method that may reallocate (push, reserve, shrink_to_fit).
Array::iter(&this) -> implement Iterator<T>
where T: CopyIterate over the elements in order, yielding each by value (bitwise copy). Gated on T: Copy for the same reason as get: a yielded owning value would alias storage the array still owns. For owning T, walk by index with length() + get_ref.
Array::insert(mut &this, index: u64, value: T) -> voidInsert value at index, shifting later elements right by one. index == length appends. Panics if index > length. Panics on allocation failure; use the Result-returning forms for recovery via try_push if you need fallibility on the common (append) path.
type struct Box<T, A = GlobalAlloc> where A: Allocator {
ptr: T*;
alloc: A;
}Box<T, A>: single-owner heap allocation.
std::alloc::boxfunction name(count: i32, args...)A variadic parameter: the trailing bucket receives any number of further arguments with C's calling convention, so the function stays ABI-compatible with the printf family. Wrap the bucket in VaArgs to read typed values from it.
Array::try_push(mut &this, value: T) -> Result<(), AllocError>Array::set(mut &this, index: u64, value: T) -> voidOverwrite the element at index, taking ownership of value. The previous occupant is released in place before the slot is reused: a raw slot store (this.ptr[index] = value) does NOT drop the destination, so for owning T (String, Box<T>, ...) the old element's resources would otherwise leak.
Array::first(&this) -> Option<T*>First element by shared borrow, or None if empty. Sound for every T (the array keeps ownership). Invalidated by any reallocating method.
Option::NoneArray::last(&this) -> Option<T*>Last element by shared borrow, or None if empty.
Array::index_of(&this, value: &T) -> Option<u64>
where T: EqIndex of the first element equal to value, or None. Linear scan; T: Eq.
Array::contains(&this, value: &T) -> boolean
where T: EqTrue if some element equals value. T: Eq.
Array::reverse(mut &this) -> voidReverse the elements in place. Sound for owning T: each pair is exchanged with a three-step move (identical to mem::swap's body, inlined here so the method stays self-contained - see note below).
Array::remove(mut &this, index: u64) -> TRemove and return the element at index, shifting later elements left by one to preserve order (O(n)). Panics if out of range. For O(1) removal when order doesn't matter, use swap_remove.
Array::truncate(mut &this, new_length: u64) -> voidShorten to at most new_length, releasing the truncated elements in place. A no-op if new_length >= length. Keeps capacity.
Array::clear(mut &this) -> voidRelease every initialized element (the [0, length) prefix) in place, then reset the length to zero while keeping the backing capacity. Mirrors drop's element teardown so Array<String>, Array<Box<...>>, and similar owning shapes don't leak their contents.
Array::sort(mut &this) -> void
where T: OrdSort the array in place, ascending, by T::compare.
Array::sort_by(mut &this, less: (&T, &T) -> boolean) -> voidSort in place using a user-supplied "less-than" predicate. Returns no value; mutates the array. Same complexity and stability as sort(). The predicate must impose a strict weak ordering (irreflexive, transitive, with the implied equivalence being transitive) or the result is unspecified.
Array::append(mut &this, source: Slice<T>) -> void
where T: CopyAppend every element of source to the end of this array. Panics on allocation failure; use try_append to recover.
Array::try_append(mut &this, source: Slice<T>) -> Result<(), AllocError>
where T: CopyFallible bulk append. Reserves space for all elements first so partial copies are impossible; either all elements are appended or none are. Gated on T: Copy (see append): the append is a bitwise memcpy out of the borrowed source.
Array::resize(mut &this, new_length: u64, value: T) -> void
where T: CopySet the length to exactly new_length, filling any new slots with value. Shrinking drops the elements above new_length, exactly as truncate does; growing leaves every slot initialized, so the whole [0, new_length) range is readable afterwards.
Array::try_resize(mut &this, new_length: u64, value: T) -> Result<(), AllocError>
where T: CopyFallible resize. Reserves the whole growth up front, so the array is either resized or left exactly as it was - never partially grown.
Array::reserve_exact(mut &this, additional: u64) -> Result<(), AllocError>Array::resize_storage(mut &this, new_capacity: i64) -> Result<(), AllocError>new T { field: value }
new E::Variant(args)
new T[n]Heap allocation. new T { .. } places a struct literal on the heap and yields a T*, and new E::V(args) does the same for an enum variant; new T[n] reserves n uninitialised T - the typed malloc. The storage comes from T's Allocate implementation, or else the global allocator. Parentheses after a struct's name are refused (E0117): there are no constructors, and a struct's static new(..) is an ordinary method.
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 parameter Twhere T: Drop
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.
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 parameter Twhere T: Clone
type trait Default {
static default() -> This;
}Default: a canonical "zero value" for a type.
std::core::defaulttype parameter Twhere T: Eq
type parameter Twhere T: Hash
type trait Index<Idx, Output> {
index(&this, idx: Idx) -> Output*;
}Index<Idx, Output> is the contract for container[idx]-style access, returning a pointer to the element. The compiler rewrites a[i] into *(a.index(i)); because the deref of the returned Output* is a place, the one impl serves reads (v = a[i]), writes (a[i] = v), and compound assignment (a[i] += v).
primitive usizePointer-width unsigned integer; the natural type for sizes and indices.
primitive typetype parameter Twhere T: Display
type trait Display {
fmt<W>(&this, f: mut &Formatter<W>) -> Result<(), FmtError>
where W: FmtWrite;
}Display / Debug / Formatter.
std::fmt::displaytype parameter Twhere T: Debug
type trait Debug {
fmt<W>(&this, f: mut &Formatter<W>) -> Result<(), FmtError>
where W: FmtWrite;
}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 from_iter<I, T>(it: I) -> Array<T>
where I: Iterator<T>Collect every element an iterator yields into a fresh Array<T>, in order. it is consumed. T is recovered from the iterator's Iterator<T> impl, and the result element type is fixed by the expected type at the call site:
type parameter Iwhere I: Iterator
(parameter) it: I