join slice to string golang
package main
import (
"fmt"
"strings"
)
func main() {
slice := []string{"Hello", "world", "Golang"}
result := strings.Join(slice, " ")
fmt.Println(result)
}
Explanation:
package main
: Declares the package asmain
, indicating that this Go file will be compiled into an executable program.import ( "fmt" "strings" )
: Imports necessary packages.fmt
is used for formatted I/O, andstrings
provides string manipulation functions.func main() { ... }
: Defines the main function, which serves as the entry point of the program.slice := []string{"Hello", "world", "Golang"}
: Declares and initializes a string slice namedslice
with three string elements: "Hello", "world", and "Golang".result := strings.Join(slice, " ")
: Uses theJoin
function from thestrings
package to concatenate the elements of theslice
with a space" "
in between, and assigns the result to the variableresult
.fmt.Println(result)
: Prints the concatenated stringresult
to the standard output.