0
0
GoHow-ToBeginner · 3 min read

How to Use strings.HasPrefix in Go: Simple Guide

In Go, use strings.HasPrefix to check if a string starts with a specific prefix. It returns true if the string begins with the prefix, otherwise false. Import the strings package to use this function.
📐

Syntax

The strings.HasPrefix function takes two arguments: the full string and the prefix string. It returns a boolean value indicating if the full string starts with the prefix.

  • strings.HasPrefix(s, prefix string) bool
  • s: The string to check.
  • prefix: The prefix to look for at the start of s.
  • Returns true if s starts with prefix, otherwise false.
go
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "golang programming"
	prefix := "go"
	result := strings.HasPrefix(s, prefix)
	fmt.Println(result) // true
}
Output
true
💻

Example

This example shows how to use strings.HasPrefix to check different prefixes in a string and print the results.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "hello world"

	fmt.Println(strings.HasPrefix(text, "he"))    // true
	fmt.Println(strings.HasPrefix(text, "hello")) // true
	fmt.Println(strings.HasPrefix(text, "world")) // false
	fmt.Println(strings.HasPrefix(text, ""))      // true (empty prefix always matches)
}
Output
true true false true
⚠️

Common Pitfalls

Some common mistakes when using strings.HasPrefix include:

  • Forgetting to import the strings package.
  • Confusing HasPrefix with case-insensitive checks (it is case-sensitive).
  • Expecting it to check anywhere in the string instead of only at the start.
  • Using nil or empty strings incorrectly.

Always remember strings.HasPrefix is case-sensitive and only checks the start of the string.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "GoLang"

	// Wrong: case-insensitive check (this returns false)
	fmt.Println(strings.HasPrefix(text, "go"))

	// Right: exact case match
	fmt.Println(strings.HasPrefix(text, "Go"))
}
Output
false true
📊

Quick Reference

FunctionDescriptionReturns
strings.HasPrefix(s, prefix string)Checks if string s starts with prefixbool (true or false)
Case sensitivityThe check is case-sensitiveN/A
Empty prefixAlways returns true if prefix is emptytrue
ImportRequires importing the strings packageN/A

Key Takeaways

Use strings.HasPrefix to check if a string starts with a specific prefix in Go.
Remember that HasPrefix is case-sensitive and only checks the start of the string.
Always import the strings package before using HasPrefix.
An empty prefix always returns true when checked with HasPrefix.
Use exact case matches to get correct results with HasPrefix.