Transform Runes With strings.Map

Apply per-rune transformations with strings.Map: replace characters, drop runes by returning negative values, and see the result stay a fresh string.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	// 每个符文过一次映射函数:统一转大写以外的自定义规则
	leet := strings.Map(func(r rune) rune {
		switch r {
		case 'a':
			return '4'
		case 'e':
			return '3'
		}
		return r // 其余原样保留
	}, "arena")
	fmt.Println("mapped:", leet)

	// 返回负值表示删除该符文:剔除空格
	compact := strings.Map(func(r rune) rune {
		if unicode.IsSpace(r) {
			return -1
		}
		return r
	}, "go pro tips")
	fmt.Println("compact:", compact)

	// 原字符串不可变:Map 总是产生新字符串
	source := "arena"
	fmt.Println("source unchanged:", source)
}

Inside the snippet

Transform Runes With strings.Map is built around the function main.

Putting it to use

The demo output is labeled (mapped:, compact:, source unchanged:), so every line in the printed output names the step that produced it.

Core lines

return r // 其余原样保留

Interactive Tools for This Topic

FAQ

What does Transform Runes With strings.Map print when run?
Running the file directly is enough — expect labeled output lines such as `mapped:`, `compact:`, `source unchanged:`.