小编典典

golang将字符串添加到slice…interface {}

go

我有一个作为参数的方法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

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


阅读 281

收藏
2020-07-02

共1个答案

小编典典

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]
2020-07-02