How to convert a string to an array in Golang?
How to convert a string to an array of strings with one element (i.e. that string) in Go effectively.
For example:
var s string
s = "This is a string"
to
["This is a string"]
Obviously, one way would be to make an array of strings and initialize the first element as that string but I am looking for an effective approach.
Solution 1:
To initialize a string slice in Go, you use s := []string{"This is a string"}
.
To initialize a string array in Go, you use s := [1]string{"This is a string"}
.
The only difference (in declaring each) lies in specifying the array length or not.
To understand which structure you want to use, you should read more about the difference between slices
and arrays
on the Go Blog.