Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extension methods in golang?

Tags:

.net

go

I am a .NET guy. Very much new to the Go language.

In .NET we have extension methods. Is there anything equivalent in Go?

In .NET I will do like bsonTrans["trans.ticket"]

in that bsonTrans => bson document

    "trans.ticket" => key in json

     trans is outer level and

     ticket is inner level

I am using native mongodb driver. In that I add my extension functions to perform these operations.

Like wise up to the nth level I did it .NET.

I would like to apply the same logic in Go.

Example

 b := []byte(trans)
var config map[string]interface{}
err := json.Unmarshal(b, &config)

fmt.Println(config["data"].(map[string] interface{})["issued"])

For instance in that example, can i do something like:

config["data.issued"] which should give the value in return ?

Please help me in figuring this out...

Actual json :-

(The actual json is too big, however I am providing a sample of it with less fields.)

{
 "_id" : 2001,
    "address" : {
        "line1" : "",
        "line2" : "",
        "line3" : ""
       },
    "tickets" : [ 
        {
            "seq" : 2,
            "add" : [
              {
              "seq" : "",
              "amnt" : 50
              },

              {
              "seq" : "",
              "amnt" : 50
              {
              "seq" : "",
              "amnt" : 50
              }
              }

              }
             ]
}

Reason for not using struct is my json has too many nested structures and I have more than 10 schemas with different structures.

So I left out structs.

I admit that I am not sure that omitting structs is the best way.

like image 568
shanmugharaj Avatar asked Mar 03 '14 17:03

shanmugharaj


Video Answer


3 Answers

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()
}
like image 149
definitelycarter Avatar answered Sep 24 '22 21:09

definitelycarter


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()
}
like image 39
Mohsen Avatar answered Sep 23 '22 21:09

Mohsen


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)

}
like image 31
Cory LaNou Avatar answered Sep 24 '22 21:09

Cory LaNou