Ubuntu下Golang编译出现乱码,通常由字符编码不一致导致,可按以下步骤解决:
检查并设置系统编码
locale 命令,确认 LANG 和 LC_ALL 为 UTF-8(如 en_US.UTF-8 或 zh_CN.UTF-8)。sudo dpkg-reconfigure locales # 选择UTF-8编码
echo 'export LANG=en_US.UTF-8' >> ~/.bashrc
echo 'export LC_ALL=en_US.UTF-8' >> ~/.bashrc
source ~/.bashrc
确保终端编码为UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
处理Golang程序编码
golang.org/x/text/encoding 包统一编码(如UTF-8):import "golang.org/x/text/encoding/unicode"
// 示例:将GBK转换为UTF-8
decoder := unicode.UTF8.NewDecoder()
utf8Reader := decoder.Reader(bytes.NewReader(gbkBytes))
检查日志库配置
EncoderConfig 指定UTF-8编码。安装中文字体(如需显示中文)
sudo apt-get install fonts-wqy-microhei fonts-wqy-zenhei
验证:编译后查看输出是否正常显示,若仍有乱码,检查具体代码中字符串处理逻辑是否涉及非UTF-8编码。