bac*_*chr 15 arrays go slice prepend
我有一个作为参数的方法v ...interface{},我需要在前面添加一个string.这是方法:
func (l Log) Error(v ...interface{}) {
  l.Out.Println(append([]string{" ERROR "}, v...))
}
当我尝试使用append()它不起作用:
> 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
在这种情况下,前置的正确方法是什么?
icz*_*cza 26
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]
| 归档时间: | 
 | 
| 查看次数: | 17721 次 | 
| 最近记录: |