Skip to content

proposal: generic: smarter generic type inference #71960

Closed as not planned
Closed as not planned
@shuqingzai

Description

@shuqingzai

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions