prepend a string to the beginning of another string in go

To prepend a string s2 to the beginning of another string s1 in Go, you can use the + operator to concatenate the two strings.

main.go
s1 := "bar"
s2 := "foo"

result := s2 + s1

fmt.Println(result) // Output: "foobar"
84 chars
7 lines

Alternatively, you can use the strings package's Join function to concatenate the two strings.

main.go
s1 := "bar"
s2 := "foo"

result := strings.Join([]string{s2, s1}, "")

fmt.Println(result) // Output: "foobar"
111 chars
7 lines

Note that the + operator and Join function both create a new string every time they are called, which can be inefficient if you need to perform many concatenations. For better performance, you can use a strings.Builder or a bytes.Buffer to build the concatenated string efficiently.

gistlibby LogSnag