rust-ownership-system
Use when Rust's ownership system including ownership rules, borrowing, lifetimes, and memory safety. Use when working with Rust memory management.
What this skill does
# Rust Ownership System
Master Rust's unique ownership system that provides memory safety without
garbage collection through compile-time checks.
## Ownership Rules
**Three fundamental ownership rules:**
1. Each value in Rust has a variable that's its owner
2. There can only be one owner at a time
3. When the owner goes out of scope, the value is dropped
```rust
fn ownership_basics() {
// s owns the String
let s = String::from("hello");
// Ownership moved to s2
let s2 = s;
// Error: s no longer owns the value
// println!("{}", s);
println!("{}", s2); // OK
} // s2 dropped here, memory freed
```
## Move Semantics
**Ownership transfer (move):**
```rust
fn move_semantics() {
let s1 = String::from("hello");
// Ownership moved to function
takes_ownership(s1);
// Error: s1 no longer valid
// println!("{}", s1);
}
fn takes_ownership(s: String) {
println!("{}", s);
} // s dropped here
// Return ownership from function
fn gives_ownership() -> String {
String::from("hello")
}
fn main() {
let s = gives_ownership();
println!("{}", s);
}
```
**Copy trait for stack types:**
```rust
fn copy_types() {
// Types implementing Copy are duplicated, not moved
let x = 5;
let y = x; // x copied to y
println!("x: {}, y: {}", x, y); // Both valid
// Copy types: integers, floats, bool, char, tuples of Copy types
let tuple = (1, 2.5, true);
let tuple2 = tuple;
println!("{:?} {:?}", tuple, tuple2); // Both valid
}
```
## Borrowing
**Immutable borrowing (references):**
```rust
fn immutable_borrow() {
let s1 = String::from("hello");
// Borrow s1 (immutable reference)
let len = calculate_length(&s1);
println!("Length of '{}' is {}", s1, len); // s1 still valid
}
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope, but doesn't drop the value
// Multiple immutable borrows allowed
fn multiple_immutable_borrows() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
let r3 = &s;
println!("{}, {}, {}", r1, r2, r3); // OK
}
```
**Mutable borrowing:**
```rust
fn mutable_borrow() {
let mut s = String::from("hello");
// Mutable borrow
change(&mut s);
println!("{}", s); // "hello, world"
}
fn change(s: &mut String) {
s.push_str(", world");
}
// Only ONE mutable borrow allowed at a time
fn mutable_borrow_rules() {
let mut s = String::from("hello");
let r1 = &mut s;
// let r2 = &mut s; // Error: cannot borrow mutably twice
println!("{}", r1);
}
// Cannot mix mutable and immutable borrows
fn no_mix_borrows() {
let mut s = String::from("hello");
let r1 = &s; // Immutable borrow
let r2 = &s; // Another immutable borrow
// let r3 = &mut s; // Error: cannot borrow mutably while immutably borrowed
println!("{} {}", r1, r2);
}
```
**Non-lexical lifetimes (NLL):**
```rust
fn non_lexical_lifetimes() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} {}", r1, r2);
// r1 and r2 no longer used after this point
// OK: immutable borrows ended
let r3 = &mut s;
println!("{}", r3);
}
```
## Lifetimes
**Lifetime annotations:**
```rust
// Lifetime 'a ensures returned reference lives as long as both inputs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string");
let string2 = String::from("short");
let result = longest(&string1, &string2);
println!("Longest: {}", result);
}
```
**Lifetime in structs:**
```rust
// Struct holds a reference, needs lifetime annotation
struct ImportantExcerpt<'a> {
part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention: {}", announcement);
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
let excerpt = ImportantExcerpt {
part: first_sentence,
};
println!("{}", excerpt.part);
}
```
**Lifetime elision rules:**
```rust
// Compiler infers lifetimes in these cases:
// Rule 1: Each reference parameter gets its own lifetime
fn first_word(s: &str) -> &str {
// Expanded: fn first_word<'a>(s: &'a str) -> &'a str
s.split_whitespace().next().unwrap_or("")
}
// Rule 2: If one input lifetime, assign to all outputs
fn foo(s: &str) -> &str {
s
}
// Rule 3: If &self or &mut self, its lifetime assigned to outputs
impl<'a> ImportantExcerpt<'a> {
fn get_part(&self) -> &str {
// Expanded: fn get_part<'a>(&'a self) -> &'a str
self.part
}
}
```
**Static lifetime:**
```rust
// 'static means reference lives for entire program duration
fn static_lifetime() -> &'static str {
"This string is stored in binary"
}
// String literals have 'static lifetime
let s: &'static str = "hello world";
```
## Smart Pointers
**Box for heap allocation:**
```rust
fn box_pointer() {
// Allocate value on heap
let b = Box::new(5);
println!("b = {}", b);
} // b deallocated when out of scope
// Recursive types require Box
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn recursive_type() {
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}
```
**Rc for reference counting:**
```rust
use std::rc::Rc;
fn rc_example() {
let a = Rc::new(5);
// Clone Rc pointer, increment count
let b = Rc::clone(&a);
let c = Rc::clone(&a);
println!("Reference count: {}", Rc::strong_count(&a)); // 3
// All owners must go out of scope before value is dropped
}
// Sharing data in graph structures
enum RcList {
Cons(i32, Rc<RcList>),
Nil,
}
use RcList::{Cons as RcCons, Nil as RcNil};
fn shared_ownership() {
let a = Rc::new(RcCons(5, Rc::new(RcCons(10, Rc::new(RcNil)))));
// b and c both reference a
let b = RcCons(3, Rc::clone(&a));
let c = RcCons(4, Rc::clone(&a));
}
```
**RefCell for interior mutability:**
```rust
use std::cell::RefCell;
fn refcell_example() {
let value = RefCell::new(5);
// Borrow mutably
*value.borrow_mut() += 1;
// Borrow immutably
println!("Value: {}", value.borrow());
}
// Combine Rc and RefCell for shared mutable data
use std::rc::Rc;
use std::cell::RefCell;
fn rc_refcell() {
let value = Rc::new(RefCell::new(5));
let a = Rc::clone(&value);
let b = Rc::clone(&value);
*a.borrow_mut() += 10;
*b.borrow_mut() += 20;
println!("Value: {}", value.borrow()); // 35
}
```
## Ownership Patterns
**Taking ownership vs borrowing:**
```rust
// Take ownership when you need to consume the value
fn consume(s: String) {
println!("{}", s);
}
// Borrow when you only need to read
fn read(s: &String) {
println!("{}", s);
}
// Borrow mutably when you need to modify
fn modify(s: &mut String) {
s.push_str(" modified");
}
fn main() {
let mut s = String::from("hello");
read(&s); // Still own s
modify(&mut s); // Still own s
consume(s); // No longer own s
}
```
**Builder pattern with ownership:**
```rust
struct Config {
name: String,
value: i32,
}
struct ConfigBuilder {
name: Option<String>,
value: Option<i32>,
}
impl ConfigBuilder {
fn new() -> Self {
ConfigBuilder {
name: None,
value: None,
}
}
// Take ownership and return ownership
fn name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
fn value(mut self, value: i32) -> Self {
self.value = Some(value);
self
}
fn build(self) -> Config {
Config {
name: self.name.unwrap_or_default(),
value: self.value.unwrap_or(0),
}
}
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.