Splitting client/server code

前端 未结 1 1960
鱼传尺愫
鱼传尺愫 2020-11-28 16:37

I\'m developing a client/server application in golang, and there are certain logical entities that exist both on client and server(the list is limited)

I would like

相关标签:
1条回答
  • 2020-11-28 17:35

    This "dead code elimination" is already done–partly–by the go tool. The go tool does not include everything from imported packages, only what is needed (or more precisely: it excludes things that it can prove unreachable).

    For example this application

    package main; import _ "fmt"; func main() {}
    

    results in almost 300KB smaller executable binary (on windows amd64) compared to the following:

    package main; import "fmt"; func main() {fmt.Println()}
    

    Excludable things include functions, types and even unexported and exported variables. This is possible because even with reflection you can't call a function or "instantiate" types or refer to package variables just by having their names as a string value. So maybe you shouldn't worry about it that much.

    Edit: With Go 1.7 released, it is even better: read blog post: Smaller Go 1.7 binaries

    So if you design your types and functions well, and you don't create "giant" registries where you enumerate functions and types (which explicitly generates references to them and thus renders them unexcludable), compiled binaries will only contain what is actually used from imported packages.

    I would not suggest to use build tags for this kind of problem. By using them, you'll have an extra responsibility to maintain package / file dependencies yourself which otherwise is done by the go tool.

    You should not design and separate code into packages to make your output executables smaller. You should design and separate code into packages based on logic.

    I would go with separating stuffs into packages when it is really needed, and import appropriately. Because this is really what you want: some code intended only for the client, some only for the server. You may have to think a little more during your design and coding phase, but at least you will see the result (what actually belongs / gets compiled into the client and into the server).

    0 讨论(0)
提交回复
热议问题