4

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.

5
  • 5
    I'm not sure I understand. [1]string{s} is the array containing the string s. Is that syntax all you're asking for? Commented Mar 25, 2017 at 9:18
  • Nope doesn't work. Getting : cannot use [1]string literal (type [1]string) as type []string in assignment Commented Mar 25, 2017 at 9:21
  • 2
    I don't think "effective" means what you think it does. The method you've described is effective. So is @DarshanRivkaWhittle 's, but his is terser and more idiomatic. Commented Mar 25, 2017 at 9:21
  • Basically I have a string array message []string so what I want to do is message = [s] Commented Mar 25, 2017 at 9:22
  • 1
    What you want is not an array but a slice. Use []string(s). Commented Mar 25, 2017 at 11:39

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

3 Comments

Hi there. Welcome to StackOverflow. Your answer should provide the essential code-snippets along with an explanation. Please explain how and why it works - this is how you write a good answer according to S.O. standards. Feel free to reference other resources and when you do, it would also be helpful, if you provide a link. stackoverflow.com/help/how-to-answer
This seems to be restating things already said years ago in the accepted answer.
Thank you, this was useful for me. I wanted to convert a string VARIABLE to a string array. The other answer doesn't show this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.