how to convert string to slice in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert string to slice in golang, use Split() method and seprator ( as per your requirement like space, hyphen etc ), it will convert string into slice.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows


Today, I will show you how do I convert string to slice in golang, as above mentioned I’m going to use Split() method.

The Split() method strings package.

Let’s start our Golang convert string to slice example

Convert whole string into slice example

main.go

package main

import (
	"fmt"
	"strings"
)

func main() {
  
  // separator space
	str := "Welcome to aguidehub"
	slice := strings.Split(str, " ");
	fmt.Println(slice) // ["Welcome", "to", "aguidehub"]
	
  // sperator empty string 	
	str1 := "aguidehub"
	slice1 := strings.Split(str1, "");
	fmt.Println(slice1) // ["a", "g", "u", "i", "d", "e", "h", "u", "b"]
	
}

In the above example, we have converted string to slice and printed in golang console. let’s check the output.

Output

[Welcome to aguidehub]
[a g u i d e h u b]

Try it Yourself

I hope it helps you, All the best 👍.