I am making use of a package that I am importing. Let’s say that the package that I am importing contains this:
package foopkg
type Foo struct{
Name string
// some othre fields
}
Because I have no access to that package and want to implement my custom methods on Foo I have created this:
package mypkg
type MyFoo foo.Foo
func (x MyFoo) MyExtensionMethodOnFoo() {
// do something
}
So now I am working with objects of type mypkg.MyFoo so that I can call my custom methods. But I often have to cast that to foopkg.Foo in order to call the methods from package foopkg.
Anyway, is there a way to perform a cast without copying an entire object? This is what I mean:
var f1* mypkg.MyFoo = new(mypkg.MyFoo)
f1.Name = "test1"
// if I want to cast f1 to foopkg.Foo I will have to do this
var f2 foopkg.Foo = foopkg.Foo(*f1)
// this copies the entire object. To prove this if I do:
f2.Name = "test2"
fmt.Println(f1.Name) // will print "test1", I want it to print "test2"
// it will be great if I could do this:
// but this does not compile:
// var f2* foopkg.Foo = foopkg.Foo(f1)
Is there a way I can convert *f1 which is of type *mypkg.MyFoo to an object of type *foopkg.Foo both pointing to the same memory address? In other words, if I change a value of f1.Name I will like that change to reflect on f2.Name even though they are of different types.
>Solution :
Use embedding:
type MyFoo struct {
foo.Foo
}
When declared like this, MyFoo will have all the methods of foo.Foo, thus you can do:
x:=MyFoo{}
x.SomeMethod()
x.MyExtensionMethod()
Above, if x.SomeMethod is a method declared for foo.Foo, then you can still call it, and it will operate on the foo.Foo part of x. The MyExtensionMethod will operate on x.
In general, if you use type embedding, the methods of the embedded types will also be the methods of the derived type. If you define a new type (without embedding), the new type will only have the methods explicitly declared for that new type, and none of the methods declared for the base type.