Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm playing with Go and run into something I'm unable to find in Google, although there is certainly something that exists:

I'm using the following struct:

type Syntax struct {
  name string
  extensions *regexp.Regexp
}

type Scanner struct {
  classifier * bayesian.Classifier
  save_file string
  name_to_syntax  map[string] *Syntax
  extensions_to_syntax  map[*regexp.Regexp] *Syntax
}

I'd like to perform the following using Go and I'm quoting ruby because it's how I'd do that using ruby:

test_regexpes = my_scanner.extensions_to_syntax.keys

My goal is to get an array of *regexp.Regexp .

Any idea on how to do that in a simple way ?

Thank you !

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Maybe a better question for SO. For example, I think http://stackoverflow.com/questions/1841443/iterating-over-all-the-keys-of-a-golang-map is close to what you want. The only thing missing from that answer is allocating the slice. Here are the two parts together,

testRegexps := make(*regexp.Regexp, len(myScanner.extensionsToSyntax))
i := 0
for k := range myScanner.extensionsToSyntax {
    testRegexps[i] = k
    i++
}
share|improve this answer
    
I wonder if there's a way to get this to approach the terseness of Ruby somehow more... –  rogerdpack Apr 22 at 14:06

For followers, if you are "mapping" from an array/slice, it can be made more terse (in this case, from string to string):

here's an equivalent of #map!

array := []string{"a", "b", "c"};
for i, s := range array { array[i] = strings.ToUpper(s) }

and an equivalent of #map (NB: could map to a different array type here if desired)

array := []string{"a", "b", "c"};
array2 := make([]string, len(array))
for i, s := range array { array2[i] = strings.ToUpper(s) }

Alternatively you might be able to clean this up using some function pointers, and it would end up something like

array2 := _map(array, strings.ToUpper)

given this method

func _map(coll []string, f func(string) string) []string {
      var newColl = make([]string, len(coll))
      for i, s := range coll {
          newColl[i] = f(s)
      }
      return newColl
}

There may be more ways to do this (libraries for the same?), such that you could get it down to something like

arr := arrays.StringArray([]string{"a", "b", "c"}).Map(func(v string) string { return strings.ToUpper(v) }); 

FWIW. test file: https://gist.github.com/anonymous/0de5f631a74c77a3da33

ref: https://groups.google.com/forum/#!topic/golang-nuts/fgaeXCUEPC4

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.