samber / lo

💥 A Lodash-style Go library based on Go 1.18+ Generics (map, filter, contains, find...)

Home Page:https://pkg.go.dev/github.com/samber/lo

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Reverse mutating?

sunjayaali opened this issue · comments

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]

@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
}

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

Good catch @xyluet !

I doubt that's expected.

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

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.

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"))

Available as an option