Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 406
Harshit Gupta Avatar asked Nov 16 '25 01:11

Harshit Gupta


2 Answers

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.

like image 200
Carsten Hagemann Avatar answered Nov 17 '25 19:11

Carsten Hagemann


intput:="This is a string"
output:=[]string{intput}
fmt.Println(intput)
fmt.Println(output)

To understand you should read more about slices and arrays on the Go Blog.

like image 44
Vikash Rai Avatar answered Nov 17 '25 18:11

Vikash Rai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!