【问题标题】:golang prepend a string to a slice ...interface{}golang 将字符串添加到切片 ...interface{}
【发布时间】:2016-03-21 12:00:25
【问题描述】:

我有一个以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

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

【问题讨论】:

标签: arrays go slice prepend


【解决方案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]

【讨论】:

  • 啊谢谢append([]interface{}{s}, rest...)为我工作
猜你喜欢
  • 2015-09-15
  • 2019-07-24
  • 2017-09-25
  • 2022-11-28
  • 2013-12-10
  • 2020-12-31
  • 2015-12-24
  • 2020-11-27
  • 2021-10-24
相关资源
最近更新 更多