-2

I'm very new with GO and don't understand some basics - so I'm really don't know how to ask ask google about it. So I have a project with 2 files, both in package main - the root of src. One file is main.go

package main

var (
    node * NodeDTO
)

func main() {
    node = &NodeDTO{ID: 1}
}

And another is dto.go with

package main

type NodeDTO struct {
    ID int
}

So main.go tells me - "undefined: NodeDTO". But if I create a dir dto near of main.go and use my NodeDTO from there like

package main

import "another_tcp_server/dto"

var (
    node * dto.NodeDTO
)

func main() {
    node = &dto.NodeDTO{ID: 1}
}

It's ok. Please tell me why this happen?

trashgenerator
  • 460
  • 7
  • 22
  • 3
    How do you compile/run the program? – tkausl Jul 10 '18 at 18:27
  • 3
    Please read through intro documentation: ["How to Write Go Code"](https://golang.org/doc/code.html), it steps through all the basics. – JimB Jul 10 '18 at 18:27
  • 1
    https://stackoverflow.com/questions/28081486/golang-multiple-files-in-main-package/28081554 – dm03514 Jul 10 '18 at 18:31
  • 3
    Possible duplicate of [How can I "go run" a project with multiple files in the main package?](https://stackoverflow.com/questions/28081486/how-can-i-go-run-a-project-with-multiple-files-in-the-main-package) – Martin Tournoij Jul 10 '18 at 18:33
  • Thanks. I run it from Goland with "Run kind: file". This is the mistake – trashgenerator Jul 10 '18 at 18:34
  • You are referencing the object as `dto.NodeDTO`, but it should just be `NodeDTO`. The prefix is used to specify an item from another package, but all of your code is in `package main`. As the others already have, I would suggest you brush up on the basics of Go. – Gavin Jul 10 '18 at 19:48
  • Man, I'm sorry - it is copy'n'paste bug - of course I don't use "dto." when they are both in package main – trashgenerator Jul 11 '18 at 03:51

1 Answers1

1

You appear to have:

$ ls
dto.go  main.go
$ cat main.go
package main

var (
    node * NodeDTO
)

func main() {
    node = &NodeDTO{ID: 1}
}
$ cat dto.go
package main

type NodeDTO struct {
    ID int
}
$ 

and you appear to run:

$ go run main.go
# command-line-arguments
./main.go:4:12: undefined: NodeDTO
./main.go:8:13: undefined: NodeDTO
$

The help for go run says, amongst other things:

$ go help run
usage: go run [build flags] [-exec xprog] package [arguments...]

Run compiles and runs the named main Go package.
Typically the package is specified as a list of .go source files,
but it may also be an import path, file system path, or pattern
matching a single known package, as in 'go run .' or 'go run my/cmd'.

You used a list of .go source files: go run main.go. You listed one file. You have two files: main.go and dto.go.

Use a complete list of .go source files:

$ go run main.go dto.go
$ 
peterSO
  • 158,998
  • 31
  • 281
  • 276