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
Release: 2024-12-07 12:57:12
Original
589 people have browsed it

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...))
}
Copy after login

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)
}
Copy after login

Output:

[first second 3]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template