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