1
votes

In Go, there are make and append functions, from which the first one let's you create a slice of the specified type, length and capacity, whereas the second one let's you append an element to the specified slice. It works more or less like in this toy example:

func main() {
    // Creates a slice of type int, which has length 0 (so it is empty), and has capacity 5.
    s := make([]int, 0, 5)

    // Appends the integer 0 to the slice.
    s = append(s, 0)

    // Appends the integer 1 to the slice.
    s = append(s, 1)

    // Appends the integers 2, 3, and 4 to the slice.
    s = append(s, 2, 3, 4)
}

Does Rust offer similar features for working with slices?

1

1 Answers

11
votes

No.

Go and Rust slices are different:

  • in Go, a slice is a proxy to another container which allows both observing and mutating the container,
  • in Rust, a slice is a view in another container which therefore only allows observing the container (though it may allow mutating the individual elements).

As a result, you cannot use a Rust slice to insert, append or remove elements from the underlying container. Instead, you need either:

  • to use a mutable reference to the container itself,
  • to design a trait and use a mutable reference to said trait.

Note: Rust std does not provide trait abstractions for its collections unlike Java, but you may still create some yourself if you think it is worth it for a particular problem.