-2

I am trying to add null value as default to struct. Is there any way to add null as default?

type Values struct {
    FirstValue string `default:"My First Value"`
    SecondValue string `default:nil` // something like that
}
Mohiuddin Khan
  • 513
  • 1
  • 5
  • 13
  • 3
    Why do you think there is a "default value", and what do you think `nil` means in a variable of type `string`? – torek Oct 12 '20 at 07:58
  • 3
    A `string` can't be `nil`. go is a statically typed language. – super Oct 12 '20 at 08:06
  • brother @torek I asked is there any way? I'm new in GO and I'm not sure about default value or assigning nil value to string. That's I'm asking is there any way? – Mohiuddin Khan Oct 12 '20 at 08:13
  • I was wondering because not that many languages even have a concept of "default value": there might be default *constructors* but not default *values* and you'd have to write a constructor function. Which you can do in Go, it's just not going to be *called* automatically. Meanwhile, strings are counted-byte-sequences, so what would a nil string *be?* – torek Oct 12 '20 at 08:20

3 Answers3

8

Strings in Go cannot be nil. Their zero value is just an empty string - "".

See https://tour.golang.org/basics/12

Also, there is no default tag in Go as each type has a zero value which is used as a "default". But, there are patterns in Go that allow you to set different "default" values, see How to set default values in Go structs.

Z. Kosanovic
  • 727
  • 4
  • 10
  • Are we just going to ignore the fact that there is no `default` tag then? – super Oct 12 '20 at 08:08
  • brother @super I'm new in go and I didn't knew about that. Is there any other way or other data type to use string and nil at the same time? – Mohiuddin Khan Oct 12 '20 at 08:16
4

In Go you can't access uninitialized memory. If you don't provide an initial value in a variable declaration, the variable will be initialized to the zero value of its type automatically.

Moreover, you can't define default values for struct fields. Unless given with a composite literal, all fields will get their zero values.

Zero value of the string type is the empty string "". If you need to store the null value, use a pointer to string. Zero value for pointers is nil:

type Values struct {
    FirstValue  string
    SecondValue *string
}
icza
  • 389,944
  • 63
  • 907
  • 827
0

maybe try this way :)

package main

import (
    "encoding/json"
    "fmt"
)

type Hoho struct {
    Name *string `json:"name"`
}

func main() {
    var nama string = "ganang"
    var h Hoho
    h.Name = NullString(nama)

    wo, _ := json.Marshal(h)
    fmt.Print(string(wo))
}

func NullString(v string) *string {
    if v == "" {
        return nil
    }

    return &v
}