Joining the string slice with a separator
The recipe, Breaking the string into words, led us through the task of splitting the single string into substrings, according to defined rules. This recipe, on the other hand, describes how to concatenate the multiple strings into a single string with a given string as the separator.
A real use case could be the problem of dynamically building a SQL select statement condition.
How to do it...
- Open the console and create the folder
chapter02/recipe03
. - Navigate to the directory.
- Create the
join.go
file with the following content:
package main import ( "fmt" "strings" ) const selectBase = "SELECT * FROM user WHERE %s " var refStringSlice = []string{ " FIRST_NAME = 'Jack' ", " INSURANCE_NO = 333444555 ", " EFFECTIVE_FROM = SYSDATE "} func main() { sentence := strings.Join(refStringSlice, "AND") fmt.Printf(selectBase+"\n", sentence) ...