Skip to content

Golang: Check if a String Starts With a Prefix

Just call the HasPrefix function from the lovely strings package:

func strings.HasPrefix(s string, prefix string) bool

Simple example code to check if a list of strings has a prefix:

package main

import (
	"fmt"
	"strings"
)

func main() {
	envList := []string{
		"env_production_value_23456789",
		"env_test_value_34567890",
		"env_production_value_87654323",
	}

	for _, env := range envList {
		if strings.HasPrefix(env, "env_production") {
			fmt.Println("production >", env)
		}
	}

}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *