First Unique Rune Via Map
Count runes with a map, then rescan for the first rune whose count is one, returning its byte index so the winner can be sliced out of the string.
Code
package main
import "fmt"
// firstUnique 返回第一个只出现一次的 rune 的字节下标,没有则返回 -1
func firstUnique(s string) int {
counts := make(map[rune]int)
for _, r := range s {
counts[r]++
}
for i, r := range s {
if counts[r] == 1 {
return i
}
}
return -1
}
func main() {
for _, s := range []string{"devexamples", "aabb", "go-go"} {
idx := firstUnique(s)
if idx >= 0 {
fmt.Printf("%s -> unique rune %q at index %d\n", s, rune(s[idx]), idx)
} else {
fmt.Printf("%s -> no unique rune\n", s)
}
}
}First Unique Rune Via Map, line by line
Everything happens inside the functions firstUnique and main.
The loop for _, r := range s is the only repeated construct.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The one function to copy reads func firstUnique(s string) int
The demo flow inside main is firstUnique — run the file to see it end to end.
Key statements
for _, s := range []string{"devexamples", "aabb", "go-go"} {
idx := firstUnique(s)
if idx >= 0 {
fmt.Printf("%s -> unique rune %q at index %d\n", s, rune(s[idx]), idx)
} else {
fmt.Printf("%s -> no unique rune\n", s)
}
}
func firstUnique(s string) int {
counts := make(map[rune]int)
for _, r := range s {
counts[r]++
}
for i, r := range s {
if counts[r] == 1 {
return i
}
}
return -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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run First Unique Rune Via Map?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.