Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved type in pointer receiver

Tags:

go

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?

like image 956
Kenenbek Arzymatov Avatar asked May 10 '18 15:05

Kenenbek Arzymatov


2 Answers

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.

like image 59
Flimzy Avatar answered Nov 16 '22 16:11

Flimzy


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.

like image 3
gushitong Avatar answered Nov 16 '22 15:11

gushitong