英文:
How to add new elements of a slice automatically to function parameter as slice grows
问题
有没有一种自动添加的方法呢?
package main
import "fmt"
func main() {
var a []string
a = append(a, "this", "this2", "this3")
increaseArguments(a)
a = append(a, "this4")
increaseArguments(a)
}
func increaseArguments(b []string) {
// 我希望,当我向切片中添加新元素时,这个函数会自动执行以下操作
// fmt.Println(b[0],b[1], b[2], b[3])
fmt.Println(b[0], b[1], b[2], b[len(b)-1])
}
在不将b[3]
作为参数添加到fmt.Println
中的情况下,有没有一种自动添加的方法呢?
英文:
Is there a way to doing this automatically ?
package main
import "fmt"
func main() {
var a []string
a = append(a, "this", "this2", "this3")
increaseArguments(a)
a = append(a, "this4")
increaseArguments(a)
}
func increaseArguments(b []string) {
// I want, when i add new element to slice i want this function act as this
// fmt.Println(b[0],b[1], b[2], b[3])
fmt.Println(b[0], b[1], b[2])
}
Instead of adding b[3] as argument to fmt.Println is there a way to add it automatically ?
答案1
得分: 1
请注意,如果b
的类型是[]any
,你可以将其作为fmt.Println()
的可变参数的值传递:
fmt.Println(b...)
但是,由于b
的类型是[]string
,你不能这样做。
但是,如果你将b
转换为[]any
切片,就可以这样做。你可以使用以下辅助函数来实现:
func convert[T any](x []T) []any {
r := make([]any, len(x))
for i, v := range x {
r[i] = v
}
return r
}
然后:
func increaseArguments(b []string) {
fmt.Println(convert(b)...)
}
这将输出以下结果(在Go Playground上尝试):
this this2 this3
this this2 this3 this4
注意:在convert()
中创建一个新的切片不会使这个解决方案变慢,因为显式传递值(如fmt.Println(b[0], b[1], b[2])
)也会隐式创建一个切片。
参考相关问题:https://stackoverflow.com/questions/52653779/how-to-pass-multiple-return-values-to-a-variadic-function
英文:
Note that if b
would be of type []any
, you could pass it as the value of the variadic parameter of fmt.Println()
:
fmt.Println(b...)
But since b
is of type []string
, you can't.
But if you transform b
into a []any
slice, you can. You can use this helper function to do it:
func convert[T any](x []T) []any {
r := make([]any, len(x))
for i, v := range x {
r[i] = v
}
return r
}
And then:
func increaseArguments(b []string) {
fmt.Println(convert(b)...)
}
This will output (try it on the Go Playground):
this this2 this3
this this2 this3 this4
Note: creating a new slice in convert()
will not make this solution any slower, because passing values explicitly (like fmt.Println(b[0], b[1], b[2])
) also implicitly creates a slice.
See related question: https://stackoverflow.com/questions/52653779/how-to-pass-multiple-return-values-to-a-variadic-function
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论