Golang slices.Compact Function

The slices.Compact function in Golang is part of the slices package, introduced in Go 1.21 as part of the standard library. This function is designed to remove consecutive duplicate elements from a slice, returning a new slice with only unique elements in their original order.

Table of Contents

  1. Introduction
  2. slices.Compact Function Syntax
  3. Examples
    • Basic Usage
    • Compacting a Slice of Strings
    • Handling Empty Slices
  4. Real-World Use Case Example
  5. Conclusion

Introduction

The slices.Compact function is useful in scenarios where you want to clean up a slice by removing consecutive duplicate elements. This is particularly helpful when working with sorted or grouped data where duplicates might appear next to each other, and you want to reduce the slice to only unique consecutive elements.

slices.Compact Function Syntax

The syntax for the slices.Compact function is as follows:

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

Parameters:

  • s S: The slice you want to compact.

Returns:

  • S: A new slice with consecutive duplicate elements removed.

Behavior:

  • Removes consecutive duplicates: The function returns a slice with only unique consecutive elements from the original slice.

Examples

Basic Usage

This example demonstrates how to use slices.Compact to remove consecutive duplicate integers from a slice.

Example

package main

import (
	"fmt"
	"slices"
)

func main() {
	// Original slice with consecutive duplicates
	slice := []int{1, 1, 2, 2, 2, 3, 4, 4, 5}

	// Use slices.Compact to remove consecutive duplicates
	compactSlice := slices.Compact(slice)

	// Print the compacted slice
	fmt.Println("Compacted slice:", compactSlice)
}

Output:

Compacted slice: [1 2 3 4 5]

Explanation:

  • The slices.Compact function removes the consecutive duplicates from the slice [1, 1, 2, 2, 2, 3, 4, 4, 5], resulting in [1, 2, 3, 4, 5].

Compacting a Slice of Strings

This example shows how to use slices.Compact to remove consecutive duplicate strings from a slice.

Example

package main

import (
	"fmt"
	"slices"
)

func main() {
	// Original slice with consecutive duplicate strings
	slice := []string{"apple", "apple", "banana", "banana", "cherry", "cherry", "cherry", "date"}

	// Use slices.Compact to remove consecutive duplicates
	compactSlice := slices.Compact(slice)

	// Print the compacted slice
	fmt.Println("Compacted slice:", compactSlice)
}

Output:

Compacted slice: [apple banana cherry date]

Explanation:

  • The slices.Compact function removes consecutive duplicate strings from the slice, resulting in a slice containing only the first occurrence of each group of duplicates.

Handling Empty Slices

This example demonstrates how slices.Compact handles an empty slice.

Example

package main

import (
	"fmt"
	"slices"
)

func main() {
	// Empty slice
	var slice []int

	// Use slices.Compact on an empty slice
	compactSlice := slices.Compact(slice)

	// Print the compacted slice
	fmt.Println("Compacted slice:", compactSlice)
}

Output:

Compacted slice: []

Explanation:

  • The slices.Compact function gracefully handles an empty slice by returning another empty slice, as there are no elements to compact.

Real-World Use Case Example: Cleaning Up Log Data

A practical use case for slices.Compact is cleaning up log data where consecutive duplicate entries might occur due to repeated events.

Example: Compacting Log Entries

package main

import (
	"fmt"
	"slices"
)

func main() {
	// Simulated log entries with consecutive duplicates
	logEntries := []string{
		"INFO: Service started",
		"INFO: Service started",
		"WARNING: High memory usage",
		"WARNING: High memory usage",
		"INFO: Service restarted",
		"INFO: Service restarted",
		"INFO: Service restarted",
	}

	// Use slices.Compact to clean up the log entries
	cleanLog := slices.Compact(logEntries)

	// Print the cleaned-up log entries
	fmt.Println("Cleaned-up log entries:", cleanLog)
}

Output:

Cleaned-up log entries: [INFO: Service started WARNING: High memory usage INFO: Service restarted]

Explanation:

  • The slices.Compact function removes consecutive duplicate log entries, helping to clean up the log and make it easier to read by retaining only the first occurrence of each group of consecutive duplicates.

Conclusion

The slices.Compact function in Go is used for removing consecutive duplicate elements from slices. It is particularly useful in scenarios where data might contain repeated values that need to be collapsed into a single instance. By using slices.Compact, you can clean up and simplify your slices, making them more efficient and easier to work with in your Go applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top