在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:alco/gostart开源软件地址:https://github.com/alco/gostart开源编程语言:开源软件介绍:This document assumes Go version 1.0.3. Table of contents
MotivationThe go tool is bundled with Go distribution by default and it's convenient for automating common tasks such as getting dependencies, building, and testing your code. It's easy to use and provides a consistent command-line interface and it also expects you to respect a bunch of conventions, some of which I find peculiar and think they introduce a slight learning curve for some users and require a bit of getting used to. While the conventions imposed by go tool might seem natural for a hardcore gopher, it takes effort for a newcomer to get up to speed with it. If you hit a wall trying to make it work for you and ask for help on #go-nuts channel or golang-nuts group showing your code layout and error messages My experience was such that neither the recommended initial reading, nor discussions on the mailing list cleared up the picture completely for me. I was only able to eventually grasp the go way by gathering tidbits from the net, through experimentation, and by looking at the go tool's source code. In this article I'm going to explain the go way from an outsider's point of view. Assuming you're likely to encounter similar hurdles along your way, this guide should answer your questions and help you understand go tool's conventions. There is also a FAQ with code samples at the bottom. The Go wayHere are some fundamentals you need to be aware of when using go tool. 1. Go tool is only compatible with code that resides in a workspaceThis is the fundamental rule of writing Go code. There are some exceptions that apply to little programs and throw-away code, but in general everything you write in Go will reside in your workspace. So what is a workspace? A workspace is a directory in your file system, the path to which is stored in the environment variable This is described in more detail in the aforementioned article and in the FAQ near the end of the present document. To keep it simple, always create a new directory inside 2. Go tool does not allow you to depend on specific versions of external packagesIf you really need to have a specific version of a certain package, you'll need to fork that package and check it out at the specific version you desire. If you need to use different versions of a single package, you'll need to create a separate fork for each version. Obviously, this approach doesn't scale and gets tedious once you need more than one version of any given package. Go's reasoning behind this is that versioning is so damn hard that your dependencies should better all be working for you at their latest versions and also at the latest versions of their respective dependencies, and so on recursively. While this is a sound advice, it is generally not possible to adhere to it in practice. You will need to depend on specific versions of your immediate dependencies or dependencies of your dependencies, etc. In a nutshell, don't try to emulate versioning with go tool, it just doesn't play well with it. 3. When working with Go tool, use fully qualified imports and always build import paths from $GOPATHThere is no such thing as local packages in Go. While local imports are possible to some extent, they're meant more for the Go devs themselves than for Go users. Anything you import is relative to your .
└── src
└── gopher
├── main.go
└── sub
└── sub.go in your main.go file you'll need to import sub as follows: package main
import "gopher/sub"
func main() {
sub.ExportedFunction()
} If you'd like to use a go package that's publicly available from some code hosting site, the recommended approach is to import it like this: import "codehosting.com/path/to/package"
func main() {
package.ExportedFunction()
} Go tool let's you download remote packages either by passing their import path to go get codehosting.com/path/to/package The source for the downloaded package will end up in Go tool doesn't do everythingComing from other languages/environments, you may expect that
FAQ0. What is GOPATH and what should I do with it?The best way to go about
If you'd like to know more about
1. How do I start writing Go code?Before you start any coding, you should pick a directory that will become your Go workspace. All your Go code will reside there. Set the export GOPATH=/Users/alco/go You'll also need to create a subdirectory named $ tree -L 2 $GOPATH
/Users/alco/go
└── src
├── example
├── gopher
└── testy Each of the subdirectories inside For more information about 2. I've written some code. How do I run it?Navigate to your package's directory and use the go tool to build and run your code. Let's assume you created a program in $ cd $GOPATH/src/example
$ ls
main.go
$ cat main.go
package main
import "fmt"
func main() {
fmt.Println("Hello world!")
} The quickest way to run it is using $ go run main.go
Hello world! If your main package is split into multiple files (see question 3 for details on how to do that), you will need to pass them all as arguments to Soon, however, you'll want to produce a binary from your Go source that you can run as a standalone executable, without using go tool. Use You can also run $ go build
$ ls
example main.go
$ ./example
Hello world!
$ go install
$ $GOPATH/bin/example
Hello world! Here we defined a main package which has a You can also define packages with other names, those are called simply packages. They are not intended to produce executable programs, but rather be included as part of some command that will provide a main package with a single See also: 3. How do I split my package into multiple files?Go treats files in a single directory as belonging to one package as long as they all have the same name in their Let's continue working on our example command. We'll add a second file named helper.go and define a helper function in it. $ cd $GOPATH/src/example
$ cat helper.go
package main
func privateHelperFunc() int {
return 25
}
# now edit main.go to call this function
$ tail -3 main.go
func main() {
fmt.Println("Hello world! My lucky number is", privateHelperFunc())
} Now we cannot simply $ go run main.go
# command-line-arguments
./main.go:6: undefined: privateHelperFunc
$ go run *.go
Hello world! My lucky number is 25
$ go build
$ ./example
Hello world! My lucky number is 25 Private (non-exported) functions and data are accessible in all files that belong to a single package. A main package allows only one Finally, you can also split any other package into multiple files, not just the main ones. Go's standard packages use this ability pervasively. 4. How do I split my package into multiple subpackages?Subpackages are just separate packages that happen to reside in another package's directory. Go doesn't treat them in any special way, so import paths for subpackages are relative to your Let's create a subdirectory in our example project called math and create a file there named math.go. $ cat math/math.go
package math
func Mul2(x int) int {
return x * 2
} Let's also edit main.go to call Mul2(). $ cat main.go
package main
import (
"fmt"
"example/math" // just "math" would not work, it would import std package math
)
func main() {
fmt.Println("Hello world! My lucky number is", math.Mul2(privateHelperFunc()))
}
$ go run *.go
Hello world! My lucky number is 50 Note that if you were to replace 5. How do I create a package for others to use (i.e. a non-main package)?In the previous questions we were mainly looking at writing so called commands — packages that declare The other flavor of Go packages is used as libraries or modules in other languages, you can't build them into an executable. Their purpose is to be imported into another package (not necessarily main package) to provide useful functionality to that package. You create a package the same way as you would create a command. The only difference is that instead of Let's say we have created a package called util that resides in $ cd $GOPATH/src/util
$ cat main.go # file name is arbitrary and doesn't make any significance to Go
package util
import "math"
func Square(x float32) float32 {
return x * x
}
func Circle(r float32) float32 {
return math.Pi * r * r
}
func cube(x float32) float32 {
return x * x * x
}
$ go build
# no output In the context of a simple (non-main) package, In our util package, there are two exported functions ( See also this wiki page, it describes the process of publishing and using remote packages. 6. Where did output from running 'go build' and 'go install' go?Those two behave a bit differently depending on whether you're building a command (a main package) or a simple package. When building a main package, the resulting executable will be placed in the current directory. Running Running See also: 7. How do I set up multiple workspaces?Short answer — you don't. Go tool does expect you to work in a single workspace. You can add more than one to your So while adding more than one path to See also question 14 for one example of using multiple workspaces. 8. Can I create a package outside of $GOPATH?No. You can change your 9. What if I want to hack on some (possibly throw-away) code outside of $GOPATH?If you're not going to import anything outside of standard library or have one level of local imports, then it'll work for you with go tool. If, however, you need to use fully qualified imports, you have to move your code to a workspace or else you'll get problems when trying to Workarounds are possible for particular cases and those can be provided by another tool. In general, however, you have to stick to Go's conventions to make it work for you. 10. How do I download remote packages?To get all dependencies for the current package: go get ./... To download a particular remote package: go get <package import path> # see 'go help packages' for details
# for instance,
go get github.com/user/package All downloaded packages end up in go get -d github.com/user/package 11. How do I distinguish between library packages and main packages?Both kinds of packages live side by side in your workspace's src directory, so there's no distinction at the file system level. There is a convention to call the former ones simply packages and the latter ones commands. So, if your package's first line reads 12. Does it make sense to keep commands and packages in separate workspaces?I'd recommend against that. Using multiple workspaces is tricky, you'll need to remember to adjust 13. Can I import commands in my code?Sure, but you'll need to provide an alias during import so that the package's import chef "github.com/user/chef" 14. What if I don't want to use code hosting domains in my import paths?Don't let it bother you. This is a practice already widely adopted by the Go community. It also works well with If you're still curious, you can actually move stuff around inside Keeping remote packages in another directory, separate from your own packages, would certainly be great. And it can be emulated by specifying more than one path in Using multiple workspaces has its issues though. See question 7 for more details. 15. How do I manage package versions?There is no widely adopted solution for package version management, currently. The go tool has no knowledge of package versions; though it does choose package versions (vcs tags) based on your current go version. The currently accepted approach is to build all of your dependencies off of master. Running Before you get up in arms and race off to write your own package version manager, be sure to read through discussion of the previous attempts at this: 16. How do I freeze packages when deploying?go tool does not provide any way to create a reproducible environment for fool-proof deployments. If you tested your code locally, you can never be sure that it'll work during your next deploy, because one of the dependencies might introduce a breaking change during the time period between your testing and deployment. Use dep to manage and lock your dependencies. It's not a part of the toolchain yet, but going to be included in the future releases. 17. Where can I find more information about learning Go?Take a look at this list of official Go talks. Those are most helpful to start getting into the mindset of a Go programmer. Wish they were mentioned more prominently on the official Go site. 18. What is the current state of editor support for Go? |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论