Golang bytes.Cut() Function

Golang bytes.Cut() function is “used to cut slices s around the first instance of sep, returning the text before and after sep.” The bytes.Cut() function is a new function added to the bytes package in Go 1.18.

The found result reports whether sep appears in the s. If sep does not appear in the s, cut returns s, nil, false.

Syntax

func Cut(s, sep []byte) (before, after []byte, found bool)

Parameters

  1. s: The s parameter is the byte slice to be sliced.
  2. sep: The sep parameter is the separator to be used for slicing.

Return value

The cut() function returns three values: before, after, and found.

  1. The before value is the byte slice before the first occurrence of the separator.
  2. The after value is the byte slice after the first occurrence of the separator.
  3. The found value is a boolean indicating whether the separator was found in the byte slice.

Example 1

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("Hello, world!")
  before, after, found := bytes.Cut(s, []byte(", "))
  fmt.Println(string(before))
  fmt.Println(string(after))
  fmt.Println(found)
}

Output

Hello
world!
true

Example 2

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("Go is awesome")
  before, after, found := bytes.Cut(s, []byte("Python"))
  fmt.Println(string(before))
  fmt.Println(string(after))
  fmt.Println(found)
}

Output

Go is awesome

false

Example 3

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("This is a test")
  before, after, found := bytes.Cut(s, []byte("is"))
  fmt.Println(string(before))
  fmt.Println(string(after))
  fmt.Println(found)
}

Output

bytes.Cut() Function

That’s it!

Related posts

Golang bytes.Count()

Golang bytes.ContainsRune()

Golang bytes.ContainsFunc()

Golang bytes.ContainsAny()

Golang bytes.Contains()

Golang bytes.Clone()

Leave a Comment