Home >Backend Development >Golang >How to Prepend a String to a Variadic Interface{} Slice in Go?

How to Prepend a String to a Variadic Interface{} Slice in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 12:57:12633browse

How to Prepend a String to a Variadic Interface{} Slice in Go?

Prepending a String to a Variable Argument Slice in Go

In Go, the append() function allows you to append elements to a slice of the same type. However, when dealing with a method that accepts a variable argument slice of type ...interface{}, appending a string directly using append("some string", v) results in an error.

To successfully prepend a string to the variable argument slice, you need to use a slice of interface{} values. This is because ...interface{} allows for elements of any type. To achieve this, you can wrap the initial string in a []interface{} slice:

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

This wraps the ERROR string in a []interface{} slice, which can then be appended to the variable argument slice v.

Here's an example:

package main

import "fmt"

func main() {
  s := "first"
  rest := []interface{}{"second", 3}

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

Output:

[first second 3]

The above is the detailed content of How to Prepend a String to a Variadic Interface{} Slice in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn