Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Update arrays-and-slices.md - added slices package tip #722

Merged
merged 1 commit into from
Dec 18, 2023

Conversation

swamisriman
Copy link
Contributor

Added a line telling about the new "slices" package available from Go 1.21 which has slices.Equal, and that it has no issues with type

@quii
Copy link
Owner

quii commented Dec 18, 2023

Nice one, thanks

@quii quii merged commit 722ec79 into quii:main Dec 18, 2023
1 check passed
@swamisriman
Copy link
Contributor Author

swamisriman commented Dec 19, 2023

@quii
Sorry, it just occurred to me.
Does the slices.Equal function do a shallow check or deep check?

In the source code, they are using != to compare.
So, I assume it's a shallow compare.
https://cs.opensource.google/go/x/exp/+/master:slices/slices.go;l=24

@swamisriman swamisriman deleted the patch-1 branch December 19, 2023 09:11
@quii
Copy link
Owner

quii commented Dec 19, 2023

Yes, so it will only work with things that are comparable. With a nested slice (e.g a 2d array), it wont compile because slices are not comparable


import (
	"slices"
	"testing"
)

func TestSlicesEqual(t *testing.T) {

	t.Run("one-level slices", func(t *testing.T) {
		a := []int{1, 2, 3}
		b := []int{1, 2, 3}

		if !slices.Equal(a, b) {
			t.Fatal("strange")
		}
	})
	
	t.Run("nested", func(t *testing.T) {
		a := [][]int{
			{1, 2, 3},
			{4, 5, 6},
		}
		b := [][]int{
			{1, 2, 3},
			{4, 5, 6},
		}
		if !slices.Equal(a, b) {
			t.Fatal("strange")
		}
	})
	
}

(second test wont compile)

Could you maybe raise a 2nd PR just to clear that up for people? What do you think?

@swamisriman
Copy link
Contributor Author

swamisriman commented Dec 20, 2023

@quii
Should we add a special sub-heading for slice comparison?
As we are just introducing slices here, I didn't explain any further details as it felt like straying off the actual topic.

Or shall I just talk about the comparable part?

@swamisriman
Copy link
Contributor Author

@quii
Raised #724

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.

2 participants