golang prepend a string to a slice …interface{}

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

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

问题

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

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

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

  1. > append("some string", v)
  2. append 的第一个参数必须是切片有未命名的字符串类型
  3. > append([]string{"some string"}, v)
  4. 无法将类型 []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:

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

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

  1. > append("some string", v)
  2. first argument to append must be slice; have untyped string
  3. > append([]string{"some string"}, v)
  4. cannot use v (type []interface {}) as type string in append

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

答案1

得分: 44

append() 只能追加与切片元素类型匹配的值:

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

因此,如果你的元素是 []interface{} 类型,你需要将初始的 string 包装在 []interface{} 中才能使用 append()

  1. s := "first"
  2. rest := []interface{}{"second", 3}
  3. all := append([]interface{}{s}, rest...)
  4. fmt.Println(all)

输出结果(在 Go Playground 上尝试):

  1. [first second 3]
英文:

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

  1. 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():

  1. s := "first"
  2. rest := []interface{}{"second", 3}
  3. all := append([]interface{}{s}, rest...)
  4. fmt.Println(all)

Output (try it on the Go Playground):

  1. [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:

确定