DEV Community

Cover image for Slicing in Go
bluepaperbirds
bluepaperbirds

Posted on

2

Slicing in Go

In Go you can easily slice strings or arrays. As the name implies, a slice is a subset of the whole.

This is unlike C where you would have to use strcpy or other tricks to slice a string. (this is a lot of work)

Not so in Golang, to take a slice is much easier.

String slice in Go

You can slice a string simply by using brackets and start and end index, as if you were using Python.

The format to slice is:

a[low : high]

So to slice from 1 to 3, you would use

a[1:4]

A string slice example is shown below. First a string (st) is defined. Then it's sliced and given as input to the Println function:

package main

import "fmt"

func main() {
    st := "Hello World"
    fmt.Println(st[1:3])
}

If you run the program it will output a slice of the string st:

el

Program exited.

To grab the first word, use st[0:5]. You can do this for arrays too!

package main

import "fmt"

func main() {
    primes := [6]int{2, 3, 5, 7, 11, 13}

    var s []int = primes[1:4]
    fmt.Println(s)
}

Here we define an array of primes and then take a slice out of that. That slice is stored as a new variable and shown to the screen.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay