unicode.IsGraphic And IsPrint

Classify runes into printable categories with unicode.IsGraphic and IsPrint, seeing exactly which control and space characters each accepts.

GoData Integrity

Code

gosnippet
37 lines
package main

import (
	"fmt"
	"unicode"
)

func main() {
	samples := []rune{
		'A', '中', 'Ω', '3', '·', // 字母/数字/符号
		' ',                        // ASCII 空格
		0x00A0,                     // NBSP:Latin-1 不换行空格
		0x3000,                     // 全角空格
		'\t', '\n', 0x0007,        // 控制字符
	}

	for _, r := range samples {
		fmt.Printf("U+%04X graphic=%-5t print=%-5t letter=%t\n",
			r, unicode.IsGraphic(r), unicode.IsPrint(r), unicode.IsLetter(r))
	}

	// 文档化的唯一差别在空格:IsPrint 只收 ASCII 空格(U+0020),
	// IsGraphic 收全部 Zs 空格类(NBSP、全角空格等)
	space := rune(' ')
	nbsp := rune(0x00A0)
	fmt.Println("space graphic:", unicode.IsGraphic(space), "print:", unicode.IsPrint(space))
	fmt.Println("nbsp graphic:", unicode.IsGraphic(nbsp), "print:", unicode.IsPrint(nbsp))

	// 过滤输入里的不可见字符:保留 IsGraphic,丢掉其余
	var visible []rune
	for _, r := range "name=ada\x1b[0m" {
		if unicode.IsGraphic(r) {
			visible = append(visible, r)
		}
	}
	fmt.Println("visible only:", string(visible))
}

Glyph classes at the boundary

unicode.IsGraphic And IsPrint is built around the function main.

Iteration happens inside for _, r := range samples — everything outside it runs once.

Points of care

  • The unicode package from the standard distribution is the sole import.

Putting it to use

Signature: func main()

Every stage stamps its own line (U+, space graphic:, nbsp graphic:), so the classification verdicts stay readable.

Calls that decide visibility

for _, r := range "name=ada\x1b[0m" {
	if unicode.IsGraphic(r) {
		visible = append(visible, r)
	}
}
fmt.Println("visible only:", string(visible))
}
for _, r := range samples {
	fmt.Printf("U+%04X graphic=%-5t print=%-5t letter=%t\n",
		r, unicode.IsGraphic(r), unicode.IsPrint(r), unicode.IsLetter(r))
}

Interactive Tools for This Topic

FAQ

What does unicode.IsGraphic And IsPrint print when run?
Running the file directly is enough — expect labeled output lines such as `U+`, `space graphic:`, `nbsp graphic:`.