Skip to content

Conversation

quexer
Copy link

@quexer quexer commented Aug 8, 2025

This PR adds a new Clone function to the slice utilities that returns a shallow copy of any slice collection.

Implementation

The Clone function uses the efficient append(collection[:0:0], collection...) pattern to create a shallow copy:

// Clone returns a shallow copy of the collection.
func Clone[T any](collection []T) []T {
	return append(collection[:0:0], collection...)
}

Usage

original := []int{1, 2, 3, 4, 5}
cloned := lo.Clone(original)

// Modifying the clone doesn't affect the original
cloned[0] = 99
fmt.Println(original) // [1 2 3 4 5]
fmt.Println(cloned)   // [99 2 3 4 5]

Features

  • Type-safe: Works with any slice type using Go generics
  • Efficient: Uses the slice reslicing pattern for optimal performance
  • Nil-safe: Properly handles nil slices by returning nil
  • Independence: Creates truly independent copies that don't share underlying arrays

Testing

Added comprehensive tests covering:

  • Various slice types (int, string)
  • Empty slices
  • Nil slices
  • Verification that modifications to cloned slices don't affect originals
  • Example tests demonstrating usage

All existing tests continue to pass, ensuring no regressions.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot AI and others added 3 commits August 8, 2025 01:51
Copy link

codecov bot commented Aug 11, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.47%. Comparing base (bededfe) to head (18cbc3c).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #656   +/-   ##
=======================================
  Coverage   94.46%   94.47%           
=======================================
  Files          18       18           
  Lines        3290     3292    +2     
=======================================
+ Hits         3108     3110    +2     
  Misses        170      170           
  Partials       12       12           
Flag Coverage Δ
unittests 94.47% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant