I have a conceptual question while working with slice
in Go.
Suppose, we want to write a function to perform an operation on a slice of strings and return the new slice. The parameters for the above-said function are the original slice of strings and the operation to be performed on the items.
Method-01: Declaring an empty slice and appending new values to it
func Operation1(original []string, converter func(string) string) []string {
var converted []string
for _, item := range original {
converted = append(converted, converter(item))
}
return converted
}
Method-02: Allocating a definite-sized slice and indexing the values.
func Operation2(original []string, converter func(string) string) []string {
// since the operation on each item cannot lead to its deletion from the slice
converted := make([]string, len(original))
for index, item := range original {
converted[index] = converter(item)
}
return converted
}
Q1. I would like to know which of the above functions/techniques for declaring and accessing elements of a slice is idiomatic in Go code.
Q2. I tried both the functions on a bunch of tests and found that Operation1
function performs slightly faster than Operation2
. Any reasons behind this observation are welcomed.
P.S: I am 3 days into learning Go and come from a Python background. I know it's off-topic, yet suggestions for helpful resources will be a plus.