borrow
import std::core::borrow; · source
Looking a stored value up by another form of it.
Types
Borrow<Q>
type trait Borrow<Q> {
borrow(&this) -> Q;
}
Borrow<Q> says that a value of this type can be read as a Q that compares and hashes as the value itself does. The hashed collections — HashMap and HashSet — take their lookup key as any Q their key type borrows as, so a HashMap<String, V> is asked with a Str, and every key type is still asked with a reference to itself:
import std::collections::hashmap::{ HashMap };
function main() -> int {
mut ages: HashMap<String, i64> = HashMap::new();
ages.insert(String::from("ada"), 36);
const name: Str = "ada";
const by_view: boolean = ages.get(name).is_some(); // a Str: no String is made to ask
const by_key: boolean = ages.get(&String::from("ada")).is_some();
return if (by_view && by_key) { 0 } else { 1 };
}
An implementation must keep the two forms in step: a == b exactly when a.borrow() == b.borrow(), and a.borrow() hashes and orders as a does. A lookup that breaks this finds nothing, or the wrong entry.
Methods
borrow(&this) -> Q;
borrow(&this) -> Q;This value read as a Q.
Implementors
implement<T> trait Borrow<&T> for T
implement<A> trait Borrow<Str> for struct String<A> where A: Allocator
std::collections::string
implement<A> trait Borrow<string> for struct String<A> where A: Allocator
std::collections::string
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 Borrow<Q> {
borrow(&this) -> Q;
}A type whose values read as a Q that compares, hashes and orders as they do: what a keyed collection's lookup takes in place of the key.
type parameter QBorrow::borrow(&this) -> QThis value read as a Q.
&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 parameter Qimport 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::hashmap;HashMap<K, V, A, H>: key-value map with amortized O(1) operations.
module pagetype struct HashMap<K, V, A = GlobalAllocator, H = SipHasher> where A: Allocator {}A map from keys to values, found by the key's hash. Keys need Hash and Eq. H is the hasher: SipHasher by default, which resists keys chosen to collide; FnvHasher is faster for trusted keys. Iteration order is unspecified; BTreeMap keeps keys sorted.
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 main() -> intmut 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 ages: HashMap<String, i64>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.
static HashMap::new() -> HashMap<K, V, GlobalAllocator, H>
where H: DefaultAn empty map backed by GlobalAllocator, hashing with H's default.
mut ages: HashMap<String, i64>HashMap::insert(mut &this, key: K, value: V) -> Option<V>
where K: Hash + Eq, H: Hasher + CopyInsert key -> value. Returns the previous value if the key was present, otherwise None. Panics on allocation failure; use try_insert to recover from OOM.
static String::from<T>(item: T) -> String
where T: DisplayA String holding item's Display text, as append appends it: String::from("hi"), String::from(65 as u32), String::from(true), String::from(some_str). Panics on allocation 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 name: Strtype 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.
const by_view: booleanHashMap::get<Q>(&this, key: Q) -> Option<V>
where K: Hash + Eq + Borrow<Q>, Q: Hash + Eq, V: Copy, H: Hasher + CopyLook up a value by key, returning a bitwise copy. Gated on V: Copy for the same reason as Array::get: handing back a duplicate of an owning value would alias storage the map still owns, double-freeing on drop. For owning V, borrow in place with get_reference (or move it out with remove).
const name: Strconst by_key: booleanreturn 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.
if (condition) { ... } else if (condition) { ... } else { ... }Branches on a parenthesised boolean condition. Bodies are always braced; there is no single-statement form. Used as an expression, both arms are required and must produce the same type: const sign = if (n < 0) { -1 } else { 1 };.
const by_view: booleanconst by_key: booleanif (condition) { ... } else { ... }The branch taken when every preceding if condition is false; else if chains another condition. In expression form the else arm is mandatory, so the expression always has a value.
type trait Borrow<Q> {
borrow(&this) -> Q;
}A type whose values read as a Q that compares, hashes and orders as they do: what a keyed collection's lookup takes in place of the key.
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 Timplement 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 Awhere A: Allocator
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.
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>, AllocationError>;
deallocate(mut &this, ptr: NonNull<u8>, layout: Layout) -> void;
reallocate(mut &this, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<u8>, AllocationError>;
}A source of heap memory: hands out blocks described by a Layout and takes them back. Collections, Box and String take an A: Allocator type parameter, so the storage strategy is the caller's choice; GlobalAllocator is the default.
primitive stringNUL-terminated raw string (u8*), matching the C ABI. Length-typed text is Str / String.