Home  >  Article  >  Backend Development  >  How to Print UTF-8 Strings Correctly in a Windows Console using Go?

How to Print UTF-8 Strings Correctly in a Windows Console using Go?

DDD
DDDOriginal
2024-11-01 01:23:28286browse

How to Print UTF-8 Strings Correctly in a Windows Console using Go?

Ensuring Proper String Output in Windows Consoles with Go

Problem:
When using a Go executable to print UTF-8 strings in a Windows console, users may encounter mangled output due to the console's default IBM850 encoding. This can lead to special characters being displayed incorrectly.

Solution:
To guarantee accurate string output in a Windows console, use the following code:

<code class="go">// Alert: This method utilizes undocumented methods and does not handle stdout redirection or error checking.
// Use with caution.

package main

import (
    "syscall"
    "unicode/utf16"
    "unsafe"
)

var modkernel32 = syscall.NewLazyDLL("kernel32.dll")
var procWriteConsoleW = modkernel32.NewProc("WriteConsoleW")

func consolePrintString(strUtf8 string) {
    strUtf16 := utf16.Encode([]rune(strUtf8))
    if len(strUtf16) == 0 {
        return
    }

    var charsWritten *uint32
    syscall.Syscall6(procWriteConsoleW.Addr(), 5,
        uintptr(syscall.Stdout),
        uintptr(unsafe.Pointer(&strUtf16[0])),
        uintptr(len(strUtf16)),
        uintptr(unsafe.Pointer(charsWritten)),
        uintptr(0),
        0)
}

func main() {
    consolePrintString("Hello ☺\n")
    consolePrintString("éèïöîôùòèìë\n")
}</code>

This code uses undocumented Windows API functions to write UTF-16 encoded strings directly to the console, bypassing the default encoding. This approach ensures that special characters are displayed correctly.

Usage:
In your Go program, you can directly call the consolePrintString function to print UTF-8 encoded strings that will be properly displayed in the Windows console.

The above is the detailed content of How to Print UTF-8 Strings Correctly in a Windows Console using Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn