Search code examples
unicodegoterminalrune

Is there an equivalent to the wcwidth() function in Go?


The POSIX function wcwidth() computes the width of a given wchar_t when printed on a terminal. For instance, wcwidth(L'A') returns 1, wcwidth(L'字') returns 2, etc. There is also a function wcswidth() which computes the width of an entire string—this is useful if combining accents are present.

Does a similar function exist in the Go standard library or the supplementary libraries? If not, is there an easy way to make something sufficiently similar?


Solution

  • Does a similar function exist in the Go standard library or the supplementary libraries?

    I believe the most popular library for this is go-runewidth.

    Example:

    package main
    
    import (
      "github.com/mattn/go-runewidth"
    )
    
    func main() {
      println(runewidth.StringWidth("A"))   // prints 1
      println(runewidth.StringWidth("字"))  // prints 2
    }