gpt4 book ai didi

go - go lang : '[]string{f(v)}...' 中的可变参数打包和解包

转载 作者:IT王子 更新时间:2023-10-29 02:16:18 24 4
gpt4 key购买 nike

我在浏览github的时候发现了这个函数:

func Accumulate(s []string, f func(st string) string) (result []string) {
for _, v := range s {
result = append(result, []string{f(v)}...)
}
return result
}

这个方法可以简化为以下,还是我遗漏了什么:

func Accumulate(s []string, f func(st string) string) (result []string) {
for _, v := range s {
result = append(result, f(v))
}
return result
}

最佳答案

您编写的版本是正确且理智的。我写了一个基准:

package p

import (
"testing"
"strings"
)

var s = []string{"hello", "world", "this", "new", "world"}

func BenchmarkAcc1(b *testing.B) {
for n := 0; n < b.N; n++ {
Accumulate(s, strings.ToUpper)
}
}

func BenchmarkAcc2(b *testing.B) {
for n := 0; n < b.N; n++ {
Accumulate2(s, strings.ToUpper)
}
}

以下是我得到的一些结果:

% go test -benchtime=10s -bench=.
testing: warning: no tests to run
PASS
BenchmarkAcc1 10000000 1510 ns/op
BenchmarkAcc2 10000000 1492 ns/op
ok _/home/satran/test 33.064s

如您所见,性能也没有提高,实际上您的版本运行得更好。

这是来源:

package p

func Accumulate(s []string, f func(st string) string) (result []string) {
for _, v := range s {
result = append(result, []string{f(v)}...)
}
return result
}

func Accumulate2(s []string, f func(st string) string) (result []string) {
for _, v := range s {
result = append(result, f(v))
}
return result
}

关于go - go lang : '[]string{f(v)}...' 中的可变参数打包和解包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28787489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com