Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

rust-mutabilityRust mutability 命令行

Agent Skill

rust-mutability 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

235

周安装

10

GitHub Stars

29

下载量

82
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rust-mutability(Rust mutability 命令行)
来源仓库:https://github.com/huiali/rust-skills
仓库路径:skills/rust-mutability
安装命令:
npx skills add https://github.com/huiali/rust-skills --skill rust-mutability
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/huiali/rust-skills --skill rust-mutability

简介

用于处理 GitHub 仓库、Issue 和 Pull Request 协作信息。

  • 适合围绕代码变更和仓库状态进行整理与查询。
  • 可结合原始 README 进一步核验具体用法。
  • 安装前建议确认权限范围和是否会触发命令执行。
  • 需注意维护状态和网络访问限制。rust-mutability 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Mutability Types

TypeControllerThread-SafeUse Case
&mut TExternal callerYesStandard mutable borrow
Cell<T>InteriorNoCopy types with interior mutability
RefCell<T>InteriorNoNon-Copy types with interior mutability
Mutex<T>InteriorYesMulti-threaded interior mutability
RwLock<T>InteriorYesMulti-threaded read-write lock

Solution Patterns

Pattern 1: External Mutability

// Standard mutable borrow
fn increment(counter: &mut u32) {
    *counter += 1;
}

// Mutable method
impl Counter {
    fn increment(&mut self) {
        self.value += 1;
    }
}

When to use: Default choice, mutability controlled by caller.

Pattern 2: Cell for Copy Types

use std::cell::Cell;

struct State {
    count: Cell<u32>,
}

impl State {
    // Get immutable &self, mutate interior
    fn increment(&self) {
        self.count.set(self.count.get() + 1);
    }
}

When to use: Simple values (Copy types) need interior mutability.

Trade-offs: Only works with Copy types, no references.

Pattern 3: RefCell for Non-Copy Types

use std::cell::RefCell;

struct Cache {
    data: RefCell<HashMap<String, Value>>,
}

impl Cache {
    fn insert(&self, key: String, value: Value) {
        self.data.borrow_mut().insert(key, value);
    }

    fn get(&self, key: &str) -> Option<Value> {
        self.data.borrow().get(key).cloned()
    }
}

When to use: Need &mut T from &self, single-threaded.

Trade-offs: Runtime borrow checking, can panic.

Pattern 4: Mutex for Thread Safety

use std::sync::Mutex;

struct SharedState {
    data: Mutex<HashMap<String, Value>>,
}

impl SharedState {
    fn insert(&self, key: String, value: Value) {
        self.data.lock().unwrap().insert(key, value);
    }
}

When to use: Multi-threaded interior mutability.

Trade-offs: Lock contention, can deadlock.

Pattern 5: RwLock for Read-Heavy Workloads

use std::sync::RwLock;

struct Config {
    settings: RwLock<HashMap<String, String>>,
}

impl Config {
    fn get(&self, key: &str) -> Option<String> {
        self.settings.read().unwrap().get(key).cloned()
    }

    fn update(&self, key: String, value: String) {
        self.settings.write().unwrap().insert(key, value);
    }
}

When to use: Many readers, few writers.

Trade-offs: Write locks more expensive than Mutex.

Borrow Rules

At any time, you can have either:
├─ Multiple &T (immutable borrows)
└─ OR one &mut T (mutable borrow)

Never both simultaneously

Error Code Quick Reference

CodeMeaningDon't SayAsk Instead
E0596Cannot get mutable reference"add mut"Does this really need mutability?
E0499Multiple mutable borrows conflict"split borrows"Is data structure design correct?
E0502Borrow conflict"separate scopes"Why both borrows needed simultaneously?
RefCell panicRuntime borrow error"use try_borrow"Is runtime checking appropriate?

Workflow

Step 1: Choose Mutability Strategy

Single-threaded?
  Need &mut from &self?
    → RefCell<T>
  Copy type?
    → Cell<T>
  Otherwise?
    → &mut T

Multi-threaded?
  Simple atomic?
    → AtomicU64/AtomicBool
  Complex data?
    Read-heavy → RwLock<T>
    Write-heavy → Mutex<T>

Step 2: Handle Borrow Conflicts

E0499 (multiple mut borrows)?
  → Split struct into smaller pieces
  → Use Cell/RefCell for interior mutability
  → Redesign to avoid simultaneous access

E0502 (borrow conflict)?
  → Minimize borrow scopes
  → Clone data if needed
  → Restructure code flow

Step 3: Consider Trade-offs

RefCell?
  ✅ Flexible
  ❌ Runtime panics possible
  → Use in prototypes, single-threaded

Mutex?
  ✅ Thread-safe
  ❌ Lock contention
  → Profile before optimizing

RwLock?
  ✅ Many readers efficient
  ❌ Writer starvation possible
  → Use when reads >> writes

Thread-Safe Selection

Atomic Types

use std::sync::atomic::{AtomicU64, Ordering};

let counter = AtomicU64::new(0);
counter.fetch_add(1, Ordering::Relaxed);

Use when: Simple counters, flags.

Mutex

use std::sync::Mutex;

let data = Mutex::new(HashMap::new());
data.lock().unwrap().insert(key, value);

Use when: Thread-safe mutation, balanced read/write.

RwLock

use std::sync::RwLock;

let data = RwLock::new(HashMap::new());
data.read().unwrap().get(&key);  // Many readers
data.write().unwrap().insert(key, value);  // Few writers

Use when: Read-heavy workloads (10+ reads per write).

Common Pitfalls

1. Borrow Conflict

Symptom: E0499, E0502 errors

// ❌ Bad: multiple mutable borrows
let r1 = &mut data.field1;
let r2 = &mut data.field2;  // Error!

// ✅ Good: split borrows
let (field1, field2) = (&mut data.field1, &mut data.field2);

// ✅ Better: restructure
struct Data {
    part1: Part1,
    part2: Part2,
}

2. RefCell Panic

Symptom: "already borrowed" panic at runtime

// ❌ Bad: nested borrows
let cell = RefCell::new(vec![1, 2, 3]);
let borrow1 = cell.borrow();
let borrow2 = cell.borrow_mut();  // Panics!

// ✅ Good: drop first borrow
{
    let borrow1 = cell.borrow();
    // use borrow1...
}  // dropped
let borrow2 = cell.borrow_mut();  // OK

// ✅ Better: use try_borrow
if let Ok(mut b) = cell.try_borrow_mut() {
    // safe mutation
}

3. Lock Held Across Await

Symptom: Deadlock in async code

// ❌ Bad: MutexGuard across await
let guard = mutex.lock().unwrap();
async_op().await;  // DANGER

// ✅ Good: drop lock before await
let value = {
    let guard = mutex.lock().unwrap();
    guard.clone()
};  // lock dropped
async_op().await;

Review Checklist

When reviewing mutability code:

  • Mutability truly necessary (not premature)
  • Appropriate mutability type chosen (Cell/RefCell/Mutex)
  • RefCell used only in single-threaded contexts
  • Mutex/RwLock used for multi-threaded access
  • Lock scopes minimized to avoid contention
  • No locks held across .await points
  • Borrow conflicts resolved at design level
  • Runtime panics handled (try_borrow)
  • Atomic types used for simple counters/flags
  • Read-write patterns match RwLock choice

Verification Commands

# Check compilation
cargo check

# Look for borrow conflict errors
cargo check 2>&1 | grep -E "E0499|E0502|E0596"

# Run tests
cargo test

# Check for deadlocks (with loom)
cargo test --features loom

# Clippy warnings
cargo clippy -- -W clippy::mutex_atomic

Advanced Patterns

Splitting Borrows

// ✅ Split struct to enable simultaneous borrows
struct Data {
    readers: Vec<Reader>,
    writers: Vec<Writer>,
}

fn process(data: &mut Data) {
    let readers = &data.readers;
    let writers = &mut data.writers;  // OK, different fields
    // use both...
}

Interior Mutability with Shared Ownership

use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct Shared {
    inner: Arc<Mutex<Inner>>,
}

impl Shared {
    fn update(&self) {
        self.inner.lock().unwrap().modify();
    }
}

Related Skills

  • rust-ownership - Ownership and borrowing fundamentals
  • rust-concurrency - Thread-safe patterns
  • rust-unsafe - UnsafeCell and low-level mutability
  • rust-anti-pattern - Mutability anti-patterns
  • rust-performance - Lock contention optimization

Localized Reference

  • Chinese version: SKILL_ZH.md - 完整中文版本,包含所有内容

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.3%
按下载量换算27

Claude

30.73%
按下载量换算25

Cursor

17.04%
按下载量换算14

Gemini CLI

8.93%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills