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])
....
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])
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.