golang prepend a string to a slice …interface{}

huangapple go评论109阅读模式
英文:

golang prepend a string to a slice ...interface{}

问题

我有一个方法,它的参数是 v ...interface{},我需要在这个切片前面添加一个 string。以下是这个方法的代码:

func (l Log) Error(v ...interface{}) {
    l.Out.Println(append([]string{" ERROR "}, v...))
}

当我尝试使用 append() 时,它不起作用:

> append("some string", v)
append 的第一个参数必须是切片有未命名的字符串类型
> append([]string{"some string"}, v)
无法将类型 []interface {} 用作 append 中的字符串类型

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

英文:

I've a method that has as an argument v ...interface{}, I need to prepend this slice with a string. Here is the method:

func (l Log) Error(v ...interface{}) {
  l.Out.Println(append([]string{" ERROR "}, v...))
}

When I try with append() it doesn't work:

> 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

What's the proper way to prepend in this case?

答案1

得分: 44

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]
英文:

append() can only append values of the type matching the element type of the slice:

func append(slice []Type, elems ...Type) []Type

So if you have the elements as []interface{}, you have to wrap your initial string in a []interface{} to be able to use append():

s := "first"
rest := []interface{}{"second", 3}

all := append([]interface{}{s}, rest...)
fmt.Println(all)

Output (try it on the Go Playground):

[first second 3]

huangapple
  • 本文由 发表于 2015年12月15日 23:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/34293572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定