当它们的 init() 函数之间存在依赖关系时,如何将包拆分为多个文件?

我有一个包的 go 文件变得笨拙,所以我想将它拆分为多个逻辑文件。


我有当前拆分(和删节)的文件,如下所示:


// node.go

package schema


import (

    "github.com/graphql-go/graphql"

    "github.com/graphql-go/relay"

)


var nodeDefinitions *relay.NodeDefinitions


func init() {

    nodeDefinitions = relay.NewNodeDefinitions(relay.NodeDefinitionsConfig{

        IDFetcher: func(id string, info graphql.ResolveInfo) interface{} {

            ...

        },

        TypeResolve: func(value interface{}, info graphql.ResolveInfo) *graphql.Object {

            // based on the type of the value, return GraphQLObjectType

            switch value.(type) {

            default:

                return testType //Depends on the test.go

            }

        },

    })

}



//root.go

package schema


import (

    "github.com/graphql-go/graphql"

)


var Schema graphql.Schema


func init() {

    queryType := graphql.NewObject(graphql.ObjectConfig{

        Name: "Query",

        Fields: graphql.Fields{

            "version": &graphql.Field{

                 Type: versionType, //Depends on testtype.go

                 ...

            },

            "node": nodeDefinitions.NodeField, //Depends on node.go

        },

    })


    Schema, _ = graphql.NewSchema(graphql.SchemaConfig{

        Query: queryType,

    })

}


//testtype.go

package schema


import (

    "github.com/graphql-go/graphql"

    "github.com/graphql-go/relay"

)


var testType *graphql.Object


func init() {

    testType = graphql.NewObject(graphql.ObjectConfig{

        ...

        Interfaces: []*graphql.Interface{

            nodeDefinitions.NodeInterface, //Depends on node.go

        },

    })

}

然后我在main.go:


result := graphql.Do(graphql.Params{

        Schema:        schema.Schema,

        RequestString: r.URL.Query()["query"][0],

    })

go build:在排序文件名的字母顺序建立在页面中的文件node.go,然后root.go再testtype.go。


如果我重命名root.go为z.go,它将正确构建和运行。除了重命名不太理想之外,还有其他方法可以以可扩展的方式root.go使其z.go工作吗?


catspeake
浏览 155回答 1
1回答

慕尼黑的夜晚无繁华

您可以只使用一个init()函数并将所有内容放入其中。或者,如果您想init()在多个.go文件中使用多个函数,那么创建一个将被调用的“主”init 函数,init()并重命名其他 init 函数,例如initA(), initB(),并以正确的顺序从主 init 调用这些函数:func init() {    initA()    initB()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go