# Vec\<T\> — Dynamic Arrays

`Vec<T>` is the standard growable contiguous collection in Vex. It is the default choice when you need owned, mutable, resizable sequence storage.

## Creating Vectors

```vex
let! nums = Vec.new<i32>();
let! names = Vec.new<string>();
let! reserved = Vec.withCapacity<f64>(100);
let! hinted = Vec.withCap<i32>(16);
```

Use `let!` when you plan to mutate the vector.

Both `Vec.withCapacity(...)` and `Vec.withCap(...)` are present in the current prelude.

## Common Mutation Operations

| Method                 | Current Surface     |
| ---------------------- | ------------------- |
| `push(value)`          | append element      |
| `pop()`                | `Option<T>`         |
| `insert(index, value)` | `bool` success flag |
| `remove(index)`        | `Option<T>`         |
| `clear()`              | remove all elements |
| `set(index, value)`    | replace and drop old value; panic out of bounds |
| `trySet(index, value)` | `false` out of bounds; otherwise replace and drop old value |
| `extendSpan(view)`     | clone an external contiguous view |
| `extendWithin(a, b)`   | clone this Vec's range `[a, b)` onto its tail |

Example:

```vex
let! nums = Vec.new<i32>();
nums.push(10);
nums.push(20);
nums.push(30);

let last = nums.pop();
```

## Access Patterns

| Method                   | Current Surface |
| ------------------------ | --------------- |
| `get(index)`             | `Option<&T>`    |
| `getUnchecked(index)`    | `&T`            |
| `getRef(index)`          | `&T`            |
| `tryGet(index)`          | `Option<&T>`    |
| `tryGetRef(index)`       | `Option<&T>`    |
| `copyAt(index)`          | `T`             |
| `tryCopyAt(index)`       | `Option<T>`     |
| `getOr(index, fallback)` | `T`             |
| `first()` / `last()`     | `Option<&T>`    |

`get(...)` and `tryGet(...)` are the preferred safe access paths. `getRef(...)` is currently an unchecked compatibility alias for `getUnchecked(...)`, so it should be treated as low-level access rather than a safe borrow helper.

`copyAt` is an unchecked shallow read. `tryCopyAt` and `getOr` add a bounds
branch, but do not add cloning. These operations reject element types that
need destruction: a shared vector cannot transfer ownership out while retaining
the same element. Use them for `Copy` elements in ordinary application code.
For an owning `T`, borrow with `get` and call its `clone` policy explicitly,
or transfer ownership with `remove`/`pop`.

`trySet` consumes the replacement value even when the index is invalid; use
an explicit bounds check first if the caller must retain that value on failure.

## Basic Example

```vex
let! nums = Vec.new<i32>();
nums.push(10);
nums.push(20);

match nums.get(0) {
    Some(v) => { $println(v); }
    None => { $println("empty"); }
}
```

## Copying vs Borrowing

Use the right accessor for the ownership model you want:

- use `get(...)` or `tryGet(...)` when you want a bounds-checked borrowed view
- use `getRef(...)` only when the index proof is already established
- use `copyAt(...)` when you want an owned copy of a copyable element
- use `getOr(...)` when a fallback value keeps the call site simpler

## Capacity and Growth

`Vec.withCapacity<T>(n)` is useful when you roughly know the final size and want to reduce reallocation churn. `Vec.withCap<T>(n)` is a prelude alias for the same operation.

```vex
let! values = Vec.withCapacity<i64>(10);
values.push(1);
values.push(2);
```

## Bulk prefix commits

`appendPrefix(values, count)` appends the initialized prefix of a fixed Copy
array and grows the Vec when required. Bulk algorithms that already reserved a
proven upper bound can use `tryAppendPrefix(values, count)` instead: it never
allocates, returns `false` without mutation when spare capacity is insufficient,
and may preserve a fixed SIMD value as one full-width store while committing
only `count` elements to the logical length.

```vex
let! output = Vec.withCapacity<i32>(64);
let packed: [i32; 4] = [10, 30, 0, 0];
if !output.tryAppendPrefix(packed, 2 as usize) {
    $panic("reserved capacity invariant violated");
}
```

Both operations require `T: Copy`; ownership-bearing values should use
`push`, `extendSpan`, or a Clone-aware package API.

## Extending from a view or from self

Use `extendSpan(view)` for an externally borrowed `Span<T>`. Use
`extendWithin(start, end)` when the source range belongs to the destination Vec
itself:

```vex
let! values = Vec.withCapacity<i32>(4);
values.push(10);
values.push(20);
values.push(30);
values.push(40);

values.extendWithin(1 as usize, 4 as usize);
// [10, 20, 30, 40, 20, 30, 40]
```

The index-based self-source API is deliberate. Passing a `Span` borrowed from
`values` back into a call that mutably borrows `values` would create overlapping
shared and exclusive call arguments. `extendWithin` expresses the same operation
without weakening the borrow checker or LLVM alias guarantees. It reserves the
complete destination capacity before reading the range; Copy values use one
bulk transfer and owning values preserve `Clone` semantics.

## Interop with `Span<T>`

For zero-copy, non-owning views over contiguous memory, prefer [Span\<T\>](../memory/span-t.md). The current prelude exposes both `asPtr()` and `asSpan()` on `Vec<T>`.

```vex
let! values = Vec.new<i32>();
values.push(10);
values.push(20);

let view = values.asSpan();
let raw = values.asPtr();
```

Use `Vec<T>` when you need ownership and growth, and `Span<T>` when you need a
view. A view or element borrow must end before an operation that can relocate,
replace, or destroy its backing elements. Reserving capacity can reduce growth
but does not waive the exclusive mutable-borrow requirement.

Iteration through `Vec<T>.iter()` yields `&T`, so `for value in values` borrows
elements rather than transferring them. `pop` and `remove` transfer elements;
`clear` destroys them and retains the capacity. Dropping the vector destroys
its remaining elements and releases its storage.

## Practical Guidelines

1. Use `Vec<T>` as the default owned sequence container.
2. Keep the binding mutable with `let!` if you plan to call `push`, `pop`, `insert`, or `remove`.
3. Prefer safe accessors first; only use unchecked access when the proof is obvious.
4. Reach for `withCapacity(...)` in tight loops or builder-style code.

## Notes

- The method names and receiver contracts follow the VexArch prelude.
- Several accessors accept multiple integer index forms in current usage.

## Ownership in practice

- [Ownership workflows](../memory/ownership-workflows.md) — complete borrowed-parser and owned-report examples
