Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Check if string begins with a prefix in Go (Golang)

Posted on March 11, 2020March 11, 2020 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a HasPrefix method that can be used to check if a string begins with a certain prefix

Below is the signature of the function

func HasPrefix(s, prefix string) bool

Let’s look at the working code

Code:

package main

import (
    "fmt"
    "strings"
)

func main() {
    //Input string contains the prefix
    res := strings.HasPrefix("abcdef", "ab")
    fmt.Println(res)

    //Input string doesn't contain the prefix
    res = strings.HasPrefix("abcdef", "ac")
    fmt.Println(res)
}

Output:

true
false
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme