0

I cannot figure out how to initialize structure field when it is a reference type alias of the one of the number types:

package main

import (
  "fmt"
  "encoding/json"
)

type Nint64 *int64

type MyStruct struct {
   Value Nint64
}

func main() {
  data, _ := json.Marshal(&MyStruct{ Value : ?? 10 ?? })
  fmt.Println(string(data))
}

2 Answers 2

1

You can't, you will have to add an extra step playground:

func NewMyStruct(i int64) *MyStruct {
    return &MyStruct{&i}
}

func main() {
    i := int64(10)
    data, _ := json.Marshal(&MyStruct{Value: Nint64(&i)})
    fmt.Println(string(data))
    //or this
    data, _ = json.Marshal(NewMyStruct(20))
    fmt.Println(string(data))
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can I use just &i instead of Nint64(&i)? It is considered safe?
1

I don't think you want to reference to the address of an int64 ...

package main

import (
    "encoding/json"
    "fmt"
)

type Nint64 int64

type MyStruct struct {
    Value Nint64
}

func main() {
    data, _ := json.Marshal(&MyStruct{Value: Nint64(10)})

    fmt.Println(string(data))
}

http://play.golang.org/p/xafMLb_c73

1 Comment

I want to serialize struct to json with nullable numbers, like {value:null} or {value:10} - your answer changes semantic of the code as makes {value:null} impossible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.