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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试