简体   繁体   中英

How to print UTF-8 (or unicode) characters in Go (golang) on Windows

Let's have a look at this:

✓ Hello, 世界

As you can see there is a unicode checkmark and chinese/japanese characters. In go, If I use MSYS or linux environment i can easily print those characters. Even on windows. However, I am unable to see them in CMD nor in Powershell .

I got this:

电源外壳

This is my very basic code:

package main

import (
    "fmt"
)

func main() {

    fmt.Println("✓ Hello, 世界")
    // OR
    fmt.Println("\u2713 Hello, 世界")
}

Also, I have dozens of console apps and they are able to show such characters on my windows using cmd or powershell. Why go can't?

The problem for the Windows cmd and PowerShell consoles is the lack of CJK characters in fonts such as Consolas and Lucida Console. On Windows 10, change the console font to a font that supports CJK characters, for example, NSimSun or SimSun-ExtB.

For example,

font.go :

package main

import (
    "fmt"
)

func main() {
    fmt.Println("✓ Hello, 世界")
    // OR
    fmt.Println("\u2713 Hello, 世界")
}

Output (NSimSun):

Microsoft Windows [Version 10.0.17134.345]
>go version
go version devel +47cc59f31f Tue Oct 23 00:29:57 2018 +0000 windows/amd64
>go run font.go
✓ Hello, 世界
✓ Hello, 世界
>

Try running in Windows PowerShell ISE .

It has fairly good support for displaying Unicode.

CMD and PowerShell don't support Unicode fonts in the command line shell very well because they aren't really using "fonts" to display the text, but ANSI/VT code pages that translate to characters. So despite PowerShell being able to support Unicode internally, and you can pass them between objects and functions, the command line shell simply cannot display them, as the translation between code page and displaying doesn't exist. Some attempts to make Unicode a little better can be found here: Displaying Unicode in Powershell

For an interesting read on why CMD and PowerShell can't do Unicode well, see the blog post series: Windows Command-Line: Inside the Windows Console

Windows PowerShell ISE is different than running PowerShell from the command line shell as the ISE is displaying the output and doesn't have to use ANSI/VT sequences to pass commands between the shell and the PowerShell console host. And it doesn't have any legacy scripts to deal with.

Use Windows Terminal . You can get it on Microsoft Store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM