Index And LastIndex Locate Substrings
Locate substrings with strings.Index and strings.LastIndex, treat the -1 result as not-found, and restart the search after a match to find later occurrences.
Code
package main
import (
"fmt"
"strings"
)
func main() {
line := "key=val key2=val2"
// Index 找第一次出现,LastIndex 找最后一次出现
fmt.Println("first '=' at", strings.Index(line, "="))
fmt.Println("last '=' at", strings.LastIndex(line, "="))
// 找不到时返回 -1,这是与 bool 版 Contains 的关键区别
fmt.Println("absent token:", strings.Index(line, "missing"))
// 想跳过第一个匹配:从匹配位置之后继续搜索子串
second := strings.Index(line[strings.Index(line, "=")+1:], "=")
fmt.Println("second '=' at", second)
}How the logic moves
The entry point is the function main — everything else is wiring.
Watch out for
- The dependency list is empty; the runtime itself covers everything.
Applying it
The main callable is declared as func main()
Look for the first '=' at, last '=' at, absent token: prefixes in the printed output; each one names the step that printed it.
Notable lines
second := strings.Index(line[strings.Index(line, "=")+1:], "=")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Index And LastIndex Locate Substrings print when run?
- The script runs standalone; its 4 labeled outputs include `first '=' at`, `last '=' at`, `absent token:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.