extension methods in golang?

Here is a sample of code that uses your json. Your json sample wasn't valid, so I corrected it to what I think your intent was.

I think you will find using a map[string]interface{} with a deeply nested struct will not work out, but I don't know your use case, so I can't say for sure.

Here is an interactive link that runs the code as well: http://play.golang.org/p/0gtYMfBMWX

package main

import "fmt"
import "encoding/json"

func main() {
  b := []byte(`{
  "tickets": [
    {
      "add": [
        {
          "amnt": 50,
          "seq": ""
        },
        {
          "amnt": 50,
          "seq": ""
        },
        {
          "amnt": 50,
          "seq": ""
        }
      ],
      "seq": 2
    }
  ],
  "address": {
    "line3": "",
    "line2": "",
    "line1": ""
  },
  "_id": 2001
}`)
  var config map[string]interface{}
  if err := json.Unmarshal(b, &config); err != nil {
    fmt.Printf("Error: %s", err)
    return
  }

  // I'm not sure what part of the data you are trying to get at here...
  //fmt.Println(config["data"].(map[string]interface{})["issued"])

  fmt.Printf("%v\n\n", config)

  tickets := config["tickets"]
  fmt.Printf("%v\n\n", tickets)

}

Extension methods are not supported the way it is in .NET.

The closest thing you can do is create a type from string and create a method on that type:

type MyString string
func (m *MyString) Method() {
}

func main() {
    var s MyString = ""
    s.Method()
}

Update 2017:

Go does support extension methods for receiver types.

Based on type assertions in Go 1.9, you can simply add = where you define the type, then add methods to it.

type NewStruct = OldStrut
func (m *NewStruct) ExtensionMethod() {
}

To call it:

func main() {
    s := OldStruct{}
    s.ExtensionMethod()
}

Tags:

.Net

Go