There are multiple ways to join or concat strings in the golang.
Let's start with the easy one.
Originally published at https://schadokar.dev.
Using the + operator 🔧
package main
import (
"fmt"
)
func main() {
str1 := "Hello"
// there is a space before World
str2 := " World!"
fmt.Println(str1 + str2)
}
Output
Hello World!
Using Sprint, Sprintf, Sprintln ðŸ›
The fmt package has Sprint, Sprintf and Sprintln function which can format the strings using the default or custom formats.
All the Sprint
function are variadic functions.
Variadic functions can be called with any number of trailing arguments.
Sprint
Sprint
formats using the default formats and returns the resulting string.
Sprint
accepts an empty interface. It means it can take n elements of any type.
If no element of type string is passed then the resulting string will add a Space between the elements.
package main
import (
"fmt"
)
func main() {
num := 26
str := "Feb"
boolean := true
withStr := fmt.Sprint(num, str, boolean)
fmt.Println("With string: ", withStr)
withOutStr := fmt.Sprint(num, boolean)
fmt.Println("Without string: ", withOutStr)
}
Output
With string: 26Febtrue
Without string: 26 true
Sprintf
Sprintf
formats according to a format specifier and returns the resulting string.
Format Specifiers
%v the value in a default format
%s the uninterpreted bytes of the string or slice
Check all the available format specifier in the fmt
package.
You can use the
Sprintf
function to create theconnection string
of the DB.
For example we will create a Postgres Connection URL.
Connection URL format: postgres://username:password@hostname/databasename
package main
import (
"fmt"
)
func main() {
dbname := "testdb"
username := "admin"
password := "test1234"
hostname := "localhost"
connectionURL := fmt.Sprintf("postgres://%s:%s@%v/%v", username, password, hostname, dbname)
fmt.Println(connectionURL)
}
Output
postgres://admin:test1234@localhost/testdb
Sprintln
Sprintln
formats the elements or arguments using the default formats. Spaces are added between the elements and a new line is added in the end.
package main
import (
"fmt"
)
func main() {
str1 := "Hello"
str2 := "Gophers!"
msg := fmt.Sprintln(str1, str2)
fmt.Println(msg)
}
Output
Hello Gophers!
Using the Join function 🔩
The golang standard library has provided a Join function in the strings package.
The Join
function takes an array of strings and a separator to join them.
func Join(elems []string, sep string) string
The example has an array of weekdays. The Join
function will return a string of weekdays separated by ,
.
Using
Join
you can convert an array of string to a string.
package main
import (
"fmt"
"strings"
)
func main() {
weekdays := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
// there is a space after comma
fmt.Println(strings.Join(weekdays, ", "))
}
Output
Monday, Tuesday, Wednesday, Thursday, Friday
Top comments (0)