Golang adds a line to the slice ... interface {}

I have a method that has an argument v ...interface{} , I need to add this fragment using string . Here is a way:

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

When I try to use append() , it does not 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 is the correct way to add in this case?

+5
source share
1 answer

append() can only add values โ€‹โ€‹of a type corresponding to the type of the slice element:

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

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

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

Exit (try on the Go Playground ):

 [first second 3] 
+13
source

Source: https://habr.com/ru/post/1238292/


All Articles