You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言map数据类型异常:变量存key查询无输出直接传key正常

问题原因

变量查询map无结果的核心原因是输入的key和map中存储的key不相等,具体有两个触发点:

  • 测试输入def后面带有多余空格,实际输入值为def ,和map中存储的def字符串完全不匹配
  • 封装的readString函数只处理了\n换行符,没有兼容Windows系统下\r\n的换行场景,会导致读取到的字符串末尾多一个\r回车符,也会和目标key不匹配

修复方案

1. 优化输入读取逻辑,自动去除首尾空白字符

新增strings包导入,用strings.TrimSpace处理读取到的字符串,一次性解决换行符、回车符、输入首尾多余空格的问题:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings" // 新增strings包导入
)
func main(){
    type Authentication struct {
        password string
    }
    var authentication = map[string]Authentication{}

    var user1 Authentication
    user1.password = "abc"
    authentication["def"] = user1

    reader := bufio.NewReader(os.Stdin)
    usid := readString(reader)

    fmt.Println(authentication)
    fmt.Println(authentication[usid])
    fmt.Println(authentication["def"])
}
// 修改后的读取输入函数
func readString(reader *bufio.Reader) string {
    s, _ := reader.ReadString('\n')
    return strings.TrimSpace(s) // 去除首尾所有空白字符
}

2. 字符串匹配问题调试技巧

遇到同类问题时,可以打印字符串的转义内容和长度,快速定位隐藏字符差异:

fmt.Printf("usid值:%q,长度:%d\n", usid, len(usid))
fmt.Printf("字面量key值:%q,长度:%d\n", "def", len("def"))

内容的提问来源于stack exchange,提问作者desktopp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:54:04