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:
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)[1 2 99 4] [1 2 99]
[1 2 99 4] [1 2 7]Writing through b changed a. Rust splits the roles:
| Go | Rust |
|---|---|
[]int that owns and grows | Vec<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 append | a[..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:
fn main() {
let a = vec![1, 2, 3, 4];
let b = &a[..2];
b.push(99);
println!("{a:?} {b:?}");
}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:
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#
- For each Go
[]Tfield or variable, ask whether it owns the elements (useVec<T>) or only looks at someone else's (use&[T]or&mut [T]as a parameter). - Port
appendtopush,extendorextend_from_sliceon the owningVec. - 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 newVec<T>. - Where Go code takes a sub-slice to process in parallel, use
chunks_mutorsplit_at_mut: they give non-overlapping mutable slices that the compiler can prove disjoint. - Check places that kept a slice of a buffer for a long time: in Rust, a live slice stops you from changing the
Vecit 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
Vecto 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]).
Related questions#
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#
- Go blog, "Go Slices: usage and internals": https://go.dev/blog/slices-intro
- The Rust Book, "The Slice Type": https://doc.rust-lang.org/book/ch04-03-slices.html