Error on append, sub selection/slice of a string

Hi,

What is wrong in my append ?

Error: ./generator_string.go:14: cannot use letras[i:] (type []string) as type string in append

package main

import (
	"fmt"
)

var letras = []string{"a", "b", "c"}

func generate(a []string) {
	var letras_novo []string
	for i := 0; i < len(letras); i++ {
		letras_novo = append(letras_novo, letras[i])
		if len(letras_novo[i]) < len(letras) {
			letras_novo = append(letras_novo, letras[i:])
		}
	}
	fmt.Println(letras_novo)
	return
}

func main() {
	generate(letras)
}

Hey @drd0s,

Replace this line:

letras_novo = append(letras_novo, letras[i:])

With this line:

letras_novo = append(letras_novo, letras[i:]...)

Notice the ... at the end of the second line.

is there a reason why the … resolve the situation ? Thanks in advance @radovskyb

Yep.

The builtin function append has this as it’s function signature.

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

This means that for a slice of type T, append takes in a variable amount of arguments of type T as it’s second parameter. Basically, if you are appending to a []string, you can append either one or more strings to it, but you were passing it letras[i:] which is a slice, but adding the ...'s to the end of a slice unpacks it into multiple values of it’s type, in this case, unpacking letras[i:] in to multiple strings.

1 Like

got it! thanks

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.