dras2334 2018-04-29 10:44
浏览 134
已采纳

获取可为空字符串的长度

I have the following structure:

type NetAuth struct {
        Identificator *string `json:"identificator"`
        Password      *string `json:"password"`
        DeviceID      *string `json:"deviceId"`
        Type          int  `json:"type"`
}

I am trying to get the length of Identificator with len(event.Identificator) however I get Invalid argument for len

Before calling len I check if it's nil. I am coming from Java/C#/PHP background and it's my first time writing in GO.

  • 写回答

2条回答 默认 最新

  • duande1986 2018-04-29 10:54
    关注

    There is no simple len(string) concept in Go. You either need the number of bytes in the string representation or the number of characters (so called runes). For ASCII strings both values are the same while for unicode-encoded strings they are usually different.

    import "unicode/utf8"
    
    // Firt check that the pointer to your string is not nil
    if nil != event.Identificator {
        // For number of runes:
        utf8.RuneCountInString(*event.Identificator)
    
        // For number of bytes:
        len(*event.Identificator)
    }
    

    For more information you can check this answer https://stackoverflow.com/a/12668840/1201488.

    UPD: event.Identificator is a pointer to a string value in the NetAuth structure rather than a string value. So you need to dereference it first via *event.Identificator.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路