FAQ - Help and questions

How do Go slices and append map to Rust, and why can Rust not alias them?

#porting#golang#collectionspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A Go slice is a window onto an array, and append may write into memory that other slices still see. Rust separates the two ideas. A Vec owns and grows, a slice reference borrows and cannot grow, and the borrow checker forbids changing a Vec while a slice of it is alive, so the Go aliasing surprise does not compile.

Checked with rustc 1.93.0, Go 1.26.5, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

In Go, one type does two jobs. A slice value is a pointer, a length and a capacity. Slicing makes another window onto the same array, and append writes into the shared array when there is spare capacity. Code that is correct as long as nobody else holds a window onto the same array turns wrong when someone does.

Go (1.26.5), the surprise first, then the fix that limits the capacity:

go
a := []int{1, 2, 3, 4}
b := a[:2]
b = append(b, 99) // fits in b's capacity, so it overwrites a[2]
fmt.Println(a, b)
c := a[:2:2] // capacity limited to 2: append must copy
c = append(c, 7)
fmt.Println(a, c)
text
[1 2 99 4] [1 2 99]
[1 2 99 4] [1 2 7]

Writing through b changed a. Rust splits the roles:

GoRust
[]int that owns and growsVec<i32>
a[1:3] as a read-only view&a[1..3], a &[i32]
a[1:3] as a view you change&mut a[1..3], a &mut [i32]
append(s, x)v.push(x); only a Vec can grow
copy(dst, src)dst.copy_from_slice(src) or .clone_from_slice
a[:2:2] to force a copy on appenda[..2].to_vec() makes an independent Vec
len(s), cap(s)v.len(), v.capacity()

A Rust slice reference has no push, so the first half of the Go example cannot be written:

src/main.rsrust
fn main() {
    let a = vec![1, 2, 3, 4];
    let b = &a[..2];
    b.push(99);
    println!("{a:?} {b:?}");
}
text
error[E0599]: no method named `push` found for reference `&[{integer}]` in the current scope
 --> src/main.rs:4:7
  |
4 |     b.push(99);
  |       ^^^^ method not found in `&[{integer}]`

A view cannot grow what it views. To get Go's second result (an independent value with an extra element) you ask for the copy:

rust
let a = vec![1, 2, 3, 4];
let mut c = a[..2].to_vec(); // an independent Vec, like a[:2:2] followed by append
c.push(7);
// a is still [1, 2, 3, 4]; c is [1, 2, 7]

(That last snippet shows the idea and was not compiled separately; the error message above was produced by rustc 1.93.0.)

How to do it#

  1. For each Go []T field or variable, ask whether it owns the elements (use Vec<T>) or only looks at someone else's (use &[T] or &mut [T] as a parameter).
  2. Port append to push, extend or extend_from_slice on the owning Vec.
  3. Where Go code relies on a function appending to its argument and the caller seeing the change only sometimes, redesign it: take &mut Vec<T> (the caller always sees the change), or return a new Vec<T>.
  4. Where Go code takes a sub-slice to process in parallel, use chunks_mut or split_at_mut: they give non-overlapping mutable slices that the compiler can prove disjoint.
  5. Check places that kept a slice of a buffer for a long time: in Rust, a live slice stops you from changing the Vec it borrows from, and the error tells you where.

Common mistakes#

  • Porting a Go "slice of slices" as Vec<&[T]> and then trying to modify the original. Use indices, or restructure so the borrows do not overlap.
  • Cloning the whole Vec to satisfy the borrow checker instead of splitting it.
  • Expecting v[i..j] to be a value. It is unsized: always take a reference (&v[i..j]).

What happens when I index out of range?#

Both panic: Go with "index out of range", Rust with a message that states the index and the length. get(i) returns an Option instead.

Is Vec growth amortised like Go's append?#

Both grow by a factor when full. The exact policy is not part of the language promise in either, so do not depend on specific capacities.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet