user93466
user93466

Reputation: 151

Get length of nullable string

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.

Upvotes: 0

Views: 1777

Answers (2)

Ivan Velichko
Ivan Velichko

Reputation: 6709

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.

Upvotes: 2

Aristofanio Garcia
Aristofanio Garcia

Reputation: 1123

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

Upvotes: 2

Related Questions