I have type Process
in a library called lib
.
I am trying to import that library and add a method associated with type from lib
package.
func(p *lib.Process) DoSomething(pp *lib.Process)
But I have an error unresolved type 'lib'
inside of func(...)
. It ls surprising for me, because there is no error inside DoSomething
.
How is it possible to overcome it?
You cannot extend types defined in other packages. What you can do, is embed a type in another package in your own type, then extend your own type. Example:
type MyProcess struct {
lib.Process
}
func (p *MyProcess) DoSomething(...) {
// ...
}
With this method, all of the existing methods on lib.Process
will still be accessible, as well as your own.
You can't extend existing types in another package. You can define your own type or sub-package as follows.
type LibProcess lib.Process
func(p *LibProcess)DoSomething(pp *LibProcess) {}
type alias vs defintion
type LibProcess lib.Process // type defintion
type LibProcess = lib.Process // type alias
A type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.
An alias declaration binds an identifier to the given type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With