lo icon indicating copy to clipboard operation
lo copied to clipboard

Reverse mutating?

Open sunjayaali opened this issue 2 years ago • 6 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]

sunjayaali avatar Jun 20 '22 18:06 sunjayaali

@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 avatar Jul 23 '22 12:07 maksimillian1

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

maksimillian1 avatar Jul 23 '22 12:07 maksimillian1

Good catch @xyluet !

I doubt that's expected.

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

CorentinClabaut avatar Jul 28 '22 16:07 CorentinClabaut

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.

Bin-Huang avatar Nov 21 '22 11:11 Bin-Huang

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

jan-bar avatar Oct 31 '23 09:10 jan-bar

Available as an option

LixvYang avatar Dec 12 '23 08:12 LixvYang