ArnovLiere

Untitled

Jan 26th, 2021
654
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "encoding/json"
  6. )
  7.  
  8. type Value struct {
  9.     Key      string
  10.     OtherKey interface{}
  11. }
  12.  
  13. type OtherKeyValue struct {
  14.     OtherOtherKey string
  15. }
  16.  
  17. func main() {
  18.     // Construct value to marshal
  19.     val := Value{Key: "yo", OtherKey: OtherKeyValue{OtherOtherKey: "yo2"}}
  20.     fmt.Printf("Struct: %v\n", val)
  21.  
  22.     // Marshal
  23.     b, err := json.Marshal(val)
  24.     if err != nil {
  25.         fmt.Printf("Error marshalling: %s\n", err)
  26.         return
  27.     }
  28.     fmt.Printf("Marshalled: %s\n", string(b))
  29.  
  30.     // Unmarshal
  31.     var toFill Value
  32.     if err := json.Unmarshal(b, &toFill); err != nil {
  33.         fmt.Printf("Error unmarshalling: %s\n", err)
  34.         return
  35.     }
  36.     fmt.Printf("Unmarshalled: %v\n", toFill)
  37.  
  38.     // Cast
  39.     otherKeyValue, ok := toFill.OtherKey.(OtherKeyValue)
  40.     if !ok {
  41.         fmt.Println("Could not cast\n")
  42.         return
  43.     }
  44.     fmt.Printf("Other key value: %v\n", otherKeyValue)
  45. }
  46.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×