How to join a slice of strings into one string in Go?
Hello everyone! I just started learning Go and encountered a problem when working with strings. I have a slice of strings, for example:
words := []string{"Hello", "world", "from", "Go"}
I need to join all these strings into one, separating them with a space, to get the result: `"Hello world from Go"`. In other languages (e.g., in Python) I would simply use `" ".join(words)`, but there is no such method in Go. I tried writing a loop manually, but it turns out cumbersome, and I'm not sure it's efficient:
result := ""\nfor i, word := range words {\n if i > 0 {\n result += " "\n }\n result += word\n}
This works, but I've heard that string concatenation using `+=` in a loop can be slow due to constant memory allocation. Is there No answers yet.
Log in to leave an answer
Blogs