golang将一个字符串预先插入一个切片... interface {} [英] golang prepend a string to a slice ...interface{}

查看:200
本文介绍了golang将一个字符串预先插入一个切片... interface {}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个参数为 v ... interface {} 的方法,我需要在这个片段前加一个 string 。这里是方法:
$ b $ pre $ func(l Log)错误(v ... interface {}){
l .Out.Println(append([] string {ERROR},v ...))
}

当我尝试使用 append()时,它无效:

 > append(some string,v)
追加的第一个参数必须是slice;有无类型的字符串
> append([] string {some string},v)
不能使用v(type [] interface {})作为附加


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

解决方案

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

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

因此,如果您的元素为 [] interface {} ,你必须将你的初始字符串包装在 [] interface {} 中以便能够使用 append()

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

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

输出(在 Go Playground ):

  [第一秒3] 


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?

解决方案

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]

这篇关于golang将一个字符串预先插入一个切片... interface {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆