Ajuda com preenchimento de valores em um array slice

Boa tarde pessoal, tudo bem com vocês? Espero que sim!
Trabalho com Observabilidade ( Zabbix, Grafana, Prometheus ), e sou um bashista nato hehehe.
Estou aprendendo GoLang há aproximadamente 1 semana, gostaria de entender por que isso não funciona Go Playground - The Go Programming Language

Basicamente minha idéia foi fazer um loop for, que preencheria os elementos do array.

Olá e bem-vindo.
Por que o playground não funciona para você? Você pode postar o código que está tentando executar? e o outro publica suas mensagens em inglês para que possam ter mais ajuda…

saudações

1 Like

package main

import “fmt”

func main() {
var dilan string

for x := 0; x <= 10; x++ {
	if x != 10 {
		dilan += fmt.Sprintf("%v,", x)
	} else {
		dilan += fmt.Sprintf("%v", x)
	}
}

slice := []string{dilan}
fmt.Println(slice[0])

}

Thank you for the advice, Yamil_Bracho.

It seems it is working…Its stores all the string in a slice of 1 element…

1 Like

I might have expressed myself erroneously. My intention was to populate the slice array with the content of ‘dilan’ so that it becomes ‘slice := string{dilan},’ and when expanded, it should be ‘slice := string{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},’ but it fails because I can only access element 0. In other words, the attempt to index the values is not working.

Golang doesn’t work the way you want it to work. It can’t transform string “012345678910” into the slice of separated elements. For this purpose you need to create slice before the loop and append strings on every iteration. Or do you try to get string element by its index?

1 Like

Exactly, I’m learning to program, and the habits of Bash are very strong. The urge to hack things together is strong, but I’ve managed to evolve and achieve what I “wanted” in the best way. Thanks to everyone who contributed with all kinds of help.

I wanted to do this

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