英文:
golang prepend a string to a slice ...interface{}
问题
我有一个方法,它的参数是 v ...interface{}
,我需要在这个切片前面添加一个 string
。以下是这个方法的代码:
func (l Log) Error(v ...interface{}) {
l.Out.Println(append([]string{" ERROR "}, v...))
}
当我尝试使用 append()
时,它不起作用:
> append("some string", v)
append 的第一个参数必须是切片;有未命名的字符串类型
> append([]string{"some string"}, v)
无法将类型 []interface {} 用作 append 中的字符串类型
在这种情况下,正确的方法是什么?
英文:
I've a method that has as an argument v ...interface{}
, I need to prepend this slice with a string
. Here is the method:
func (l Log) Error(v ...interface{}) {
l.Out.Println(append([]string{" ERROR "}, v...))
}
When I try with append()
it doesn't work:
> append("some string", v)
first argument to append must be slice; have untyped string
> append([]string{"some string"}, v)
cannot use v (type []interface {}) as type string in append
What's the proper way to prepend in this case?
答案1
得分: 44
append()
只能追加与切片元素类型匹配的值:
func append(slice []Type, elems ...Type) []Type
因此,如果你的元素是 []interface{}
类型,你需要将初始的 string
包装在 []interface{}
中才能使用 append()
:
s := "first"
rest := []interface{}{"second", 3}
all := append([]interface{}{s}, rest...)
fmt.Println(all)
输出结果(在 Go Playground 上尝试):
[first second 3]
英文:
append()
can only append values of the type matching the element type of the slice:
func append(slice []Type, elems ...Type) []Type
So if you have the elements as []interface{}
, you have to wrap your initial string
in a []interface{}
to be able to use append()
:
s := "first"
rest := []interface{}{"second", 3}
all := append([]interface{}{s}, rest...)
fmt.Println(all)
Output (try it on the Go Playground):
[first second 3]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论