Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Reverse mutating? #160

Open
sunjayaali opened this issue Jun 20, 2022 · 7 comments · May be fixed by #189
Open

Reverse mutating? #160

sunjayaali opened this issue Jun 20, 2022 · 7 comments · May be fixed by #189

Comments

@sunjayaali
Copy link
Contributor

sunjayaali commented Jun 20, 2022

method Reverse is mutating the original collection, is this expected?

collection := []int64{1, 2, 3, 4, 5}
fmt.Println(lo.Reverse(collection))
fmt.Println(collection)

output:

[5 4 3 2 1]
[5 4 3 2 1]
@maksimillian1
Copy link

@xyluet I guess they know it because almost all methods here mutating the inputs

func Reverse[T any](collection []T) []T {
	length := len(collection)
	half := length / 2

	for i := 0; i < half; i = i + 1 {
		j := length - 1 - i
		collection[i], collection[j] = collection[j], collection[i]
	}

	return collection
}

@maksimillian1
Copy link

@xyluet I've found out this lib github.com/thoas/go-funk, not sure if it is much better, but at least "reverse" func isn't mutate an input array)

@CorentinClabaut
Copy link
Contributor

CorentinClabaut commented Jul 28, 2022

Good catch @xyluet !

I doubt that's expected.

I had a quick look and it looks like only Shuffle and Reverse have this issue.

@Bin-Huang
Copy link
Contributor

I had the same problem. And I think it will be more apparent if the Reverse method has no returned value. When it returns a slice, I will believe this is a new slice instead of the original one.

@jan-bar
Copy link

jan-bar commented Oct 31, 2023

Many libraries have used the following method to convert String to []byte. If the method modifies the original data, panic will occur.

func StringToBytes(s string) []byte {
	return unsafe.Slice(unsafe.StringData(s), len(s))
}

Just like this kind of code, panic will appear:lo.Shuffle(StringToBytes("xxx"))

@LixvYang
Copy link

Available as an option

@samber
Copy link
Owner

samber commented Jan 25, 2025

I made a copy of lo.Reverse and lo.Shuffle into mutable/ sub-package.

Legacy functions are deprecated.

@samber samber mentioned this issue Jan 25, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants