golang将一个字符串添加到切片... interface {}

时间:2015-12-15 15:51:33

标签: 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

在这种情况下,前置的正确方法是什么?

1 个答案:

答案 0 :(得分:24)

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]