Standard library / slices

slices.Compact()

Removes adjacent equal elements in place, keeping the first in each run. Clears the discarded tail; use the returned shorter slice. Expected stdout: '[1 2 1] [1 2 1 0]\n'.

Formal Syntax & Structure

go syntaxgo
func Compact[S ~[]E, E comparable](s S) S

Parameters & Attributes

NameTypeDescription
sSInput slice; may share its backing array.

Return Value

S

Removes adjacent equal elements in place, keeping the first in each run. Clears the discarded tail; use the returned shorter slice.

Working Example

Example Snippetgo
package main
import (  "fmt"  "slices")
func main() {  a := []int{1, 1, 2, 1}  fmt.Println(slices.Compact(a), a)}
Go Reference