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

How to Correctly Output UTF-8 Strings in a Windows Console with Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 10:55:02837browse

How to Correctly Output UTF-8 Strings in a Windows Console with Go?

Correctly Outputting Strings in a Windows Console with Go

When creating a Go executable that outputs UTF-8 encoded strings with special characters, it's important to consider the default encoding used by Windows consoles, which is IBM850 (code page 850). This can lead to mangled output due to incorrect character encodings.

To ensure proper output in a Windows console, the following approach can be implemented:

<code class="go">package main

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

// Retrieve a function pointer from the kernel32.dll library.
var procWriteConsoleW = syscall.NewProc("WriteConsoleW")

// Custom function to print strings directly to the console.
func consolePrintString(strUtf8 string) {
    // Encode the string into UTF-16 for Windows console compatibility.
    var strUtf16 []uint16
    strUtf16 = utf16.Encode([]rune(strUtf8))

    if len(strUtf16) < 1 {
        return
    }

    // Initialize the number of characters written to zero.
    var charsWritten uint32 = 0

    // Call WriteConsoleW to print the UTF-16 string to the console.
    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() {
    // Example strings to output to the console.
    consolePrintString("Hello ☺\n")
    consolePrintString("éèïöîôùòèìë\n")
}</code>

By calling our custom consolePrintString function, strings are printed directly to the console using the correct character encoding, ensuring the expected output of special characters.

The above is the detailed content of How to Correctly Output UTF-8 Strings in a Windows Console with 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