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

proposal: generic: smarter generic type inference #71960

Closed
shuqingzai opened this issue Feb 26, 2025 · 1 comment
Closed

proposal: generic: smarter generic type inference #71960

shuqingzai opened this issue Feb 26, 2025 · 1 comment
Labels
Milestone

Comments

@shuqingzai
Copy link

shuqingzai commented Feb 26, 2025

Proposal Details

In the following code, is it possible to make generic deduction smarter?
Keys can be applied to most scenarios, but Keys2 can cover the underlying type scenarios. In the test case, Keys2 cannot deduce Slice by itself, so the complete type indication must be written.

// Keys creates an array of the map keys.
func Keys[K comparable, V any, Map ~map[K]V](in ...Map) []k {  
    size := 0  
    for i := range in {  
       size += len(in[i])  
    }  
    result := make([]k, 0, size)  
  
    for i := range in {  
       for k := range in[i] {  
          result = append(result, k)  
       }  
    }  
  
    return result  
}


// Keys2 creates an array of the map keys.
func Keys2[K comparable, V any, Map ~map[K]V, Slice ~[]K](in ...Map) Slice {  
    size := 0  
    for i := range in {  
       size += len(in[i])  
    }  
    result := make(Slice, 0, size)  
  
    for i := range in {  
       for k := range in[i] {  
          result = append(result, k)  
       }  
    }  
  
    return result  
}

tests case

func TestKeys(t *testing.T) {  
    t.Parallel()  
    is := assert.New(t)
  
    type myMap map[string]int  
    keys := Keys(myMap{"foo": 1, "bar": 2}, myMap{"baz": 3})  
    is.Equal(keys, []string{"foo", "bar", "baz"})  
}

func TestKeys2(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	type myMap map[string]int
	type myStrings []string

	r1 := Keys[string, int, myMap, myStrings](myMap{"foo": 1, "bar": 2})

	is.IsType(r1, myStrings{}, "type preserved")
	is.Equal(r1, myStrings{"foo", "bar"})
}
@gopherbot gopherbot added this to the Proposal milestone Feb 26, 2025
@seankhliao
Copy link
Member

given ~[]K, there's no information on the exact type to use, so type inference cannot help.

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Feb 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants