我有一个作为参数的方法v ...interface{},我需要在此切片前添加string。方法如下:
v ...interface{}
string
func (l Log) Error(v ...interface{}) { l.Out.Println(append([]string{" ERROR "}, v...)) }
当我尝试append()不起作用时:
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():
[]interface{}
s := "first" rest := []interface{}{"second", 3} all := append([]interface{}{s}, rest...) fmt.Println(all)
输出(在Go Playground上尝试):
[first second 3]