Skip to content

Instantly share code, notes, and snippets.

@drnic
Created March 7, 2014 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drnic/9422101 to your computer and use it in GitHub Desktop.
Save drnic/9422101 to your computer and use it in GitHub Desktop.
Conversion of Ruby Array#map to some Golang equivalents
package main
import "fmt"
/**
* Ruby code below. How to do equivalent in Go?
people = [
{
first: "Nic",
last: "Williams"
},
{
first: "Banjo",
last: "Williams"
}
]
p people.map { |person| person["first"] }
*/
type Person struct {
first string
last string
}
type People []Person
func NewPeople() People {
return People{}
}
// Explicit method
func (people People) firstNames() []string {
firstNames := make([]string, len(people))
for i, person := range people {
fmt.Println(person.first)
firstNames[i] = person.first
}
return firstNames
}
// Reusable enumeration method
func (people People) Map(f func(*Person) string) []string {
res := make([]string, len(people))
for i, person := range people {
res[i] = f(&person)
}
return res
}
func main() {
people := People{
{"Nic", "Williams"},
{"Banjo", "Williams"},
}
proc := func(p *Person) string {
return p.first
}
fmt.Printf("%q\n", people.Map(proc))
//fmt.Printf("%#v\n", people)
//fmt.Println(people.firstNames())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment