Golang bytes.CutPrefix() Function

Golang bytes.CutPrefix() function returns s without the provided leading prefix byte slice and reports whether it found the prefix. If s doesn’t start with a prefix, CutPrefix returns s, false. If the prefix is the empty byte slice, CutPrefix returns s, true.

Syntax

func CutPrefix(s, prefix []byte) (after []byte, found bool)

Parameters

The function takes two arguments:

  1. s: It is byte slices.
  2. prefix: It is bytes slices.

Return value

The function returns s without the provided leading prefix byte slice and reports whether it found the prefix.

Example 1

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("Hello World!")
  prefix := []byte("Hello ")
  after, found := bytes.CutPrefix(s, prefix)
  fmt.Printf("%s %t\n", after, found)
}

Output

World! true

Example 2

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("Hello World!")
  prefix := []byte("Hi ")
  after, found := bytes.CutPrefix(s, prefix)
  fmt.Printf("%s %t\n", after, found)
}

Output

Hello World! false

Example 3

package main

import (
  "bytes"
  "fmt"
)

func main() {
  s := []byte("Hello World!")
  prefix := []byte("")
  after, found := bytes.CutPrefix(s, prefix)
  fmt.Printf("%s %t\n", after, found)
}

Output

Hello World! true

That’s it!

Related posts

Golang bytes.Cut()

Golang bytes.ContainsRune()

Golang bytes.ContainsFunc()

Golang bytes.ContainsAny()

Golang bytes.Contains()

Golang bytes.Clone()

Leave a Comment