rust
Rust programming patterns and ownership concepts
What this skill does
# Rust
## Overview
Rust programming patterns including ownership, lifetimes, traits, and async programming.
---
## Ownership and Borrowing
### Basic Ownership
```rust
fn main() {
// Ownership transfer (move)
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // Error: s1 is no longer valid
// Clone for deep copy
let s3 = String::from("hello");
let s4 = s3.clone();
println!("{} {}", s3, s4); // Both valid
// Copy types (stack-only data)
let x = 5;
let y = x; // Copy, not move
println!("{} {}", x, y); // Both valid
}
// Ownership and functions
fn takes_ownership(s: String) {
println!("{}", s);
} // s is dropped here
fn makes_copy(x: i32) {
println!("{}", x);
} // x goes out of scope, nothing special
fn gives_ownership() -> String {
String::from("hello")
}
fn takes_and_gives_back(s: String) -> String {
s
}
```
### Borrowing
```rust
// Immutable borrow
fn calculate_length(s: &String) -> usize {
s.len()
} // s goes out of scope but doesn't drop the value
// Mutable borrow
fn append_world(s: &mut String) {
s.push_str(" world");
}
fn main() {
let s = String::from("hello");
// Multiple immutable borrows OK
let r1 = &s;
let r2 = &s;
println!("{} {}", r1, r2);
// Mutable borrow (only one at a time)
let mut s2 = String::from("hello");
let r3 = &mut s2;
r3.push_str(" world");
println!("{}", r3);
// Cannot have mutable and immutable at same time
let mut s3 = String::from("hello");
let r4 = &s3;
// let r5 = &mut s3; // Error!
println!("{}", r4);
}
```
### Lifetimes
```rust
// Explicit lifetime annotations
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Struct with lifetime
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn level(&self) -> i32 {
3
}
fn announce_and_return(&self, announcement: &str) -> &str {
println!("Attention: {}", announcement);
self.part
}
}
// Multiple lifetimes
fn complex<'a, 'b>(x: &'a str, y: &'b str) -> &'a str
where
'b: 'a, // 'b outlives 'a
{
x
}
// Static lifetime
fn static_string() -> &'static str {
"I live forever"
}
```
---
## Structs and Enums
### Structs
```rust
#[derive(Debug, Clone, PartialEq)]
struct User {
id: u64,
email: String,
name: String,
active: bool,
}
impl User {
// Associated function (constructor)
fn new(email: String, name: String) -> Self {
Self {
id: generate_id(),
email,
name,
active: true,
}
}
// Method
fn deactivate(&mut self) {
self.active = false;
}
// Method returning reference
fn email(&self) -> &str {
&self.email
}
}
// Tuple struct
struct Color(u8, u8, u8);
struct Point(f64, f64, f64);
// Unit struct
struct AlwaysEqual;
```
### Enums
```rust
// Basic enum
enum Direction {
North,
South,
East,
West,
}
// Enum with data
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(u8, u8, u8),
}
impl Message {
fn process(&self) {
match self {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
}
}
}
// Result and Option
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err(String::from("Division by zero"))
} else {
Ok(a / b)
}
}
fn find_user(id: u64) -> Option<User> {
// ...
None
}
```
---
## Traits
```rust
// Trait definition
trait Summary {
fn summarize(&self) -> String;
// Default implementation
fn summarize_author(&self) -> String {
String::from("(unknown author)")
}
}
// Implement trait
impl Summary for User {
fn summarize(&self) -> String {
format!("{} ({})", self.name, self.email)
}
}
// Trait bounds
fn notify<T: Summary>(item: &T) {
println!("Breaking news: {}", item.summarize());
}
// Multiple trait bounds
fn notify_multiple<T: Summary + Clone>(item: &T) {
let cloned = item.clone();
println!("{}", cloned.summarize());
}
// where clause
fn some_function<T, U>(t: &T, u: &U) -> i32
where
T: Summary + Clone,
U: Clone + std::fmt::Debug,
{
// ...
0
}
// Return trait
fn create_summarizable() -> impl Summary {
User::new(
String::from("[email protected]"),
String::from("Test"),
)
}
// Trait objects (dynamic dispatch)
fn process_summaries(items: &[&dyn Summary]) {
for item in items {
println!("{}", item.summarize());
}
}
```
---
## Error Handling
```rust
use std::fs::File;
use std::io::{self, Read};
use thiserror::Error;
// Custom error with thiserror
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Parse error: {0}")]
Parse(#[from] std::num::ParseIntError),
#[error("Not found: {0}")]
NotFound(String),
#[error("Validation error: {field} - {message}")]
Validation { field: String, message: String },
}
// Using Result
fn read_file(path: &str) -> Result<String, AppError> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
// ? operator chains
fn read_username_from_file() -> Result<String, io::Error> {
let mut username = String::new();
File::open("username.txt")?.read_to_string(&mut username)?;
Ok(username)
}
// Option handling
fn find_and_process(id: u64) -> Option<String> {
let user = find_user(id)?;
let data = process_user(&user)?;
Some(data)
}
// Combinators
fn get_user_email(id: u64) -> Option<String> {
find_user(id)
.map(|user| user.email)
.filter(|email| !email.is_empty())
}
fn parse_and_double(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse::<i32>().map(|n| n * 2)
}
```
---
## Async Programming
```rust
use tokio;
use futures::future;
// Async function
async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
let response = reqwest::get(url).await?;
let body = response.text().await?;
Ok(body)
}
// Concurrent execution
async fn fetch_all(urls: Vec<&str>) -> Vec<Result<String, reqwest::Error>> {
let futures: Vec<_> = urls.iter().map(|url| fetch_data(url)).collect();
future::join_all(futures).await
}
// Select (race)
use tokio::select;
use tokio::time::{sleep, Duration};
async fn fetch_with_timeout(url: &str) -> Result<String, &'static str> {
select! {
result = fetch_data(url) => result.map_err(|_| "fetch error"),
_ = sleep(Duration::from_secs(5)) => Err("timeout"),
}
}
// Spawn tasks
async fn process_items(items: Vec<String>) {
let handles: Vec<_> = items
.into_iter()
.map(|item| {
tokio::spawn(async move {
process_item(&item).await
})
})
.collect();
for handle in handles {
if let Err(e) = handle.await {
eprintln!("Task failed: {}", e);
}
}
}
// Streams
use futures::stream::{self, StreamExt};
async fn process_stream() {
let numbers = stream::iter(vec![1, 2, 3, 4, 5]);
numbers
.map(|n| async move { n * 2 })
.buffer_unordered(3)
.for_each(|n| async move {
println!("{}", n);
})
.await;
}
// Channels
use tokio::sync::mpsc;
async fn channel_example() {
let (tx, mut rx) = mpsc::channel(32);
tokio::spawn(async move {
for i in 0..10 {
tx.send(i).await.unwrap();
}
});
while let Some(value) = rx.recv().await {
println!("Received: {}", value);
}
}
```
---
## Collections and Iterators
`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.