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

获取可为空字符串的长度

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.

图片转代码服务由CSDN问答提供 功能建议

我具有以下结构:

  type NetAuth struct {  
标识符* string`json:“ identifierator”`
密码* string`json:“ password”`
 DeviceID *字符串`json:“ deviceId”`
输入int`json:“ type”`
}  
   
 
 

我正在尝试使用 len(event.Identificator)来获取 Identificator 的长度,但是我得到了 len的无效参数

在调用len之前,我先检查它是否为nil。 我来自Java / C#/ PHP背景,这是我第一次用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.

    已采纳该答案
    打赏 评论
  • douguluan5102 2018-04-29 11:00

    You are using a pointer, so try this:

    println(len(*vlr.Identificator))
    

    For example,

    package main
    
    import (
        //"fmt"
        "encoding/json"
        "strings"
        "io"
    )
    
    type NetAuth struct {
            Identificator *string `json:"identificator"`
            Password      *string `json:"password"`
            DeviceID      *string `json:"deviceId"`
            Type          int  `json:"type"`
    }
    
    func jsondata() io.Reader {
      return strings.NewReader(`{"identificator": "0001", "password": "passkey"}`)
    }
    
    func main() {
        dec := json.NewDecoder(jsondata())
        vlr := new(NetAuth)
        dec.Decode(vlr)
        println(*vlr.Identificator)
        println(len(*vlr.Identificator))
    
    }
    

    Playground: https://play.golang.org/p/duf0tEddBsR

    Output:

    0001
    4
    
    打赏 评论

相关推荐 更多相似问题