V
V
Vasily Melnikov2018-10-26 13:41:20
go
Vasily Melnikov, 2018-10-26 13:41:20

Is it possible to write a Go function that extends a third-party package?

There is a certain package:
ext_api.go

package ext_api

type Data struct {
  a string
  b int
}

func Create() Data {
  d := Data{"text", 10}
  return d
}

func (d *Data) PrintData() {
  println(d.a)
}

And its usage:
package main

import "ext_api"

func main() {
  data := ext_api.Create()
  data.PrintData()
}

I would like to write my own function somehow, for example
func (d *Data) PrintDataEx() {
  println(d.a, " ", d.b)
}

If we try to add it to the main package, we get
"cannot define new methods on non-local type ext_api.Data"
Which is probably logical.
But if you add your file to the directory of this package with the package name package ext_api, then everything will start and work, but this is obviously wrong.
How would one do something in between these solutions. A separate file, but lying outside the third-party package...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
igorzakhar, 2018-10-26
@BacCM

Option 1 - Alias:

type MyType ext_api.Data

func (m *MyType) PrintDataEx() {...}

type MyStruct struct {
    *ext_api.Data
}

func (m *MyStruct) Method() {...}

m := &MyStruct{...}
m.Method()

It should also be taken into account that in the ext_api.Data structure, the fields must begin with a capital letter so that they are available during import.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question