max
max

Reputation: 686

Golang copy elements of object to slice

Is there any better way to apply a function to fields of an object and then copy the result to a new slice? By better I mean having a better performance than a for loop.

var tmp []string
for _, value := range some_object.some_field {
    tmp = append(tmp, do_something(value))
}

Something like:

tmp := map_copy(do_something(some_object.some_field))

With the resulting slice being:

tmp[0] = do_something(some_object.some_value[0])
tmp[1] = do_something(some_object.some_value[1])
tmp[2] = do_something(some_object.some_value[2])
....

Upvotes: 1

Views: 1512

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109405

The only performance increase you could add is allocating the correct slice capacity ahead of time.

You can still add values with append by starting with a 0 length slice:

tmp := make([]string, 0, len(some_object.some_field))
for _, value := range some_object.some_field {
    tmp = append(tmp, do_something(value))
}

Or by indexing the slices directly:

tmp := make([]string, len(some_object.some_field))
for i := range some_object.some_field {
    tmp[i] = do_something(some_object.some_field[i])
}

Upvotes: 5

Related Questions