Sign up ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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

closed as off-topic by MichaelT, durron597, Ixrec, Snowman, GlenH7 Oct 20 at 17:39

  • This question does not appear to be about software development within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

I'm voting to close this question as off-topic because it is a question of implementation, but is too old to migrate. – MichaelT Oct 19 at 0:59

2 Answers 2

up vote 1 down vote accepted

Maybe a better question for SO. For example, I think 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
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 '14 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:


share|improve this answer

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