Skip to content

Instantly share code, notes, and snippets.

@rdp
Forked from anonymous/ruby_map_demo.go
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save rdp/045099363d08ba348530 to your computer and use it in GitHub Desktop.

Select an option

Save rdp/045099363d08ba348530 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Apr 30, 2014.
    36 changes: 36 additions & 0 deletions ruby_map_demo.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    package main
    import "fmt"
    import "strings"
    // some ruby #map type things, in golang
    // mostly taken from https://groups.google.com/forum/#!topic/golang-nuts/fgaeXCUEPC4

    // apparently calling this out with specific types is faster than defining it generically to use interfaces: http://comments.gmane.org/gmane.comp.lang.go.general/43076

    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
    }

    func main() {

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

    // map!
    array = []string{"a", "b", "c"}
    for i, s := range array { array2[i] = strings.ToUpper(s) }
    fmt.Println(array2)

    // local map method
    array = []string{"a", "b", "c"}
    array2 = _map(array, strings.ToUpper)
    fmt.Println(array2)

    }