doulingqiu4349 2018-07-10 18:25
浏览 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?

  • 写回答

1条回答 默认 最新

  • dongzhunqiu4841 2018-07-11 12:27
    关注

    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
    $ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?