1

Now I’ve struct which implements this interface like following

type MyRunner struct {
    path string
}

func (r MyRunner) soSomthing(newPath string) error {
    run(path)
    return nil
}

Now I want to create the object and I got error implicit assignment of unexported field 'path' in MyRunner literal

This is how I do it

&run.MyRunnter{”a/b/c/“}

is there a way to do it without the New keyword in Go ?

Abu Hanifa
  • 2,857
  • 2
  • 22
  • 38
tj holwik
  • 163
  • 1
  • 2
  • 8
  • 1
    You're trying to access (set, get, doesn't matter) an unexported field from another package. The compiler won't let you do it, even if you're trying to use a composite literal to initialize it. – Marc Jan 30 '18 at 14:34
  • @Marc - ok but im trying to initate object why its not working , I require it... – tj holwik Jan 30 '18 at 14:36
  • 1
    Because this is the same as saying `run.MyRunner{path:"a/b/c"}`, you're still accessing the unexported field from another package. If you want your object initialized, you can have a helper in the same package: `func NewRunner(p string) *Runner { return &Runner{path: p} }`, or just export the field. – Marc Jan 30 '18 at 14:38
  • @Marc - thanks a lot, which way is prefered? – tj holwik Jan 30 '18 at 14:49
  • It ultimately depends on whether this field is supposed to be used from outside the package or not. If you don't care, make it exported. – Marc Jan 30 '18 at 14:49
  • @marc, thanks a lot, I will use your suggestion , btw how should I initiate your suggestion `func NewRunner(p string) *Runner { return &Runner{path: p} }` ? – tj holwik Jan 30 '18 at 14:52

1 Answers1

2

In Go every field starting with lower case letter is considered private and is accessible only within its package. Simply change the name to Path.

type MyRunner struct {
    Path string
}

This rule applies to other identifiers in Go: type names, function names. See Exported identifiers on documenation.

If you don't want to make the field public. Write a funciton that will act as a constructor.

type MyRunner struct {
    path string
}

func NewMyRunner(path string) *MyRunner {
    return &MyRunner{path}
}

Example from standard library container.list.New

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
  • ok thanks 1+ since I need to use it as constructor field it should be “public” , am I right? or should I use accesor methods ? – tj holwik Jan 30 '18 at 14:45