title: Does Go allow specification of an interface for a map with particular key type?
body: <p>I wrote a function that would return a sorted slice of strings from a map[string]Foo.  I'm curious what is the best way to create a generic routine that can return a sorted slice of strings from any type that is a map with strings as keys.</p>
  
  <p>Is there a way to do it using an interface specification?  For example, is there any way to do something like:</p>
  
  <pre><code>type MapWithStringKey interface {
      &lt;some code here&gt;
  }
  </code></pre>
  
  <p>To implement the interface above, a type would need strings as keys.  I could then write a generic function that returns a sorted list of keys for fulfilling types.</p>
  
  <p>This is my current best solution using the reflect module:</p>
  
  <pre><code>func SortedKeys(mapWithStringKey interface{}) []string {
      keys := []string{}
      typ := reflect.TypeOf(mapWithStringKey)
      if typ.Kind() == reflect.Map &amp;&amp; typ.Key().Kind() == reflect.String {
          switch typ.Elem().Kind() {
          case reflect.Int:
              for key, _ := range mapWithStringKey.(map[string]int) {
                  keys = append(keys, key)
              }
          case reflect.String:
              for key, _ := range mapWithStringKey.(map[string]string) {
                  keys = append(keys, key)
              }
              // ... add more cases as needed
          default:
              log.Fatalf("Error: SortedKeys() does not handle %s\n", typ)
          }
          sort.Strings(keys)
      } else {
          log.Fatalln("Error: parameter to SortedKeys() not map[string]...")
      }
      return keys
  }
  </code></pre>
  
  <p><a href="http://play.golang.org/p/ROsq9u40PP" rel="nofollow">Click for Go Playground version</a></p>
  
  <p>I'm forced to code type assertions for each supported type even though at compile time, we should know the exact type of the mapWithStringKey parameter.</p>