【问题标题】:Get length of nullable string获取可为空字符串的长度
【发布时间】:2018-10-09 16:11:59
【问题描述】:

我有以下结构:

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

我正在尝试使用 len(event.Identificator) 获取 Identificator 的长度,但是我得到 Invalid argument for len

在调用 len 之前,我检查它是否为 nil。我来自 Java/C#/PHP 背景,这是我第一次用 GO 编写代码。

【问题讨论】:

  • 你试过len(*event.Identificator) 因为 Identificator 是一个指针吗?
  • 阅读并发布整个错误消息:invalid argument event.Identificator (type *string) for len.
  • @xdrm-brackets 如果指针为nil,它将崩溃。
  • @bereal 是的,但是您告诉我们您先检查了它,这是您检查后的解决方案
  • 您忘记包含遇到问题的代码。

标签: go


【解决方案1】:

Go 中没有简单的len(string) 概念。您需要字符串表示中的字节数或字符数(所谓的符文)。对于 ASCII 字符串,这两个值是相同的,而对于 unicode 编码的字符串,它们通常是不同的。

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)
}

有关更多信息,您可以查看此答案https://stackoverflow.com/a/12668840/1201488

UPDevent.Identificator 是指向NetAuth 结构中的字符串值而不是字符串值的指针。所以你需要先通过*event.Identificator取消引用它。

【讨论】:

  • nit:ASCII 字符串 Unicode 编码的。正确的区别类似于“对于非 ASCII Unicode 编码的字符串”。
  • 更多细节:没有“Unicode 编码”字符串这样的东西,因为 Unicode 不是一种编码(它更像是一个字符集,将数字映射到字符(或更技术上正确的代码点) (可以但不需要表示字符)))。最常见的 Unicode 编码 是 UTF-8。
【解决方案2】:

你正在使用指针,所以试试这个:

println(len(*vlr.Identificator))

例如,

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))

}

游乐场:https://play.golang.org/p/duf0tEddBsR

输出:

0001
4

【讨论】:

  • 关于链接的官方 Stack Overflow 建议:“Provide context for links. 鼓励链接到外部资源,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及它存在的原因。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。”另外,你会得到更多的支持!
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多