我有一个作为参数的方法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
在这种情况下,正确的前置方式是什么?
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句