drg5577
2018-10-22 21:11 阅读 161
已采纳

如何在Windows上的Go(golang)中打印UTF-8(或unicode)字符

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:

powershell

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doupin2013 doupin2013 2018-10-23 01:32

    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, 世界
    >
    
    点赞 评论 复制链接分享
  • doushi4795 doushi4795 2018-10-22 22:58

    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.

    点赞 评论 复制链接分享

相关推荐