In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
GO language use example analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Francesc (@ francesc) is a member of the Go core team and a developer who promotes the Google Cloud platform. He is a programming language enthusiast, technical instructor of Google, and one of the creators of Go tour. This discussion was inspired by another Raquel V é lez in JSConf. Slides discussion, this discussion has been posted here.
Sourcegraph is the next generation of programming collaboration tools for searching, exploring, and reviewing code. We join GopherCon India to share how we use Go and learn how others use it, and we are honored to cooperate with liveblog in this discussion.
As one of the developers of the Go team, Francesc may come into contact with more GE language programmers than anyone else in the world. Because of this advantage, he divided the learning process of the Go language into five stages.
These stages are also valid for the learning of other languages. Understanding where you are can help you find the most effective way to improve yourself and avoid common pitfalls in each stage of your learning process.
Stage one: vegetable cuisine
Rookies use Go at this stage to create small projects or toy projects. They should take advantage of Go tour, Go playground, Go documents, and mailing lists (golang-nuts).
Func main () {fmt.Println (stringutil.Reverse ("! selpmaxe oG, olleH"))}
This is a simple example written in the Go language, and this code snippet comes from hello.go in the golang/example code base. Click to see the complete code.
An important skill, newcomers should try to learn how to ask questions correctly. Many newcomers say "Hey, this is wrong" in the mailing list, which does not provide enough information for others to understand and help them solve the problem. What others see is a post with hundreds of lines of code pasted, and no effort is spent to highlight the problems encountered.
Therefore, you should try to avoid pasting code directly to the forum. Instead, link to the code snippet using the share button of Go playground, which can be edited and run directly in the browser.
Phase 2: the explorer
Explorers have been able to use Go to write some small software, but sometimes they are still a little confused. They may not fully understand how to use the advanced features of Go, such as channels. Although they still have a lot to learn, they have mastered enough to do some useful things! They are beginning to feel the potential of Go and are excited about what they can create with Go.
There are usually two steps in the exploration phase. First, the inflated expectation reaches its peak, and you think you can do everything with Go, but you still can't understand or understand the true meaning of Go. You will probably write Go code in the patterns and idioms of the language you are familiar with, but you don't have a strong sense of what an authentic Go is. You start to try to do something like "migrate Architecture X, from Y language to go language."
After reaching the peak of expected expansion, you will encounter a low ebb of disillusionment. You start to miss the feature X of language Y, and you haven't fully mastered authentic Go at this time. You are still writing Go programs in the style of other programming languages, and you are even starting to feel frustrated. You may be using a lot of reflect and unsafe packages, but this is not a real Go. Authentic Go doesn't use those magical things.
A good example of a project generated during this exploration phase is the Martini Web framework. Martini is an early Web framework of the Go language that absorbs a lot of ideas (such as dependency injection) from Ruby's Web framework. Initially, the framework caused strong repercussions in the community, but it gradually received some criticism for its performance and debugability. Jeremy Saenz, author of the Martini framework, responded positively to the feedback from the Go community by writing a library Negroni that is more in line with the Go language specification.
Func (m * Martini) RunOnAddr (addr string) {/ / TODO: Should probably be implemented using a new instance of http.Server in place of / / calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use. / / This would also allow to improve testing when a custom host and port are passed. Logger: = m.Injector.Get (reflect.TypeOf (m.logger)). Interface (). (* log.Logger) logger.Printf ("listening on% s (% s)\ n", addr, Env) logger.Fatalln (http.ListenAndServe (addr, m))}
An interactive code snippet from the Martini framework, which is an example of an unauthentic Go. Pay attention to dependency injection with reflection packages
Func TestNegroniServeHTTP (t * testing.T) {result: = "" response: = httptest.NewRecorder () n: = New () n.Use (HandlerFunc (func (rw http.ResponseWriter, r * http.Request, next http.HandlerFunc) {result + = "foo" next (rw, r) result + = "ban"}) n.Use (func (rw http.ResponseWriter, r * http.Request) Next http.HandlerFunc) {result + = "bar" next (rw, r) result + = "baz"})) n.Use (HandlerFunc (func (rw http.ResponseWriter, r * http.Request, next http.HandlerFunc) {result + = "bat" rw.WriteHeader (http.StatusBadRequest)}) n.ServeHTTP (response, (* http.Request) (nil) expect (t, result, "foobarbatbazban") expect (t Response.Code, http.StatusBadRequest)}
Interactive code snippet from the Negroni library, which is an example of authentic Go
Other languages often rely on third-party libraries when providing core functions such as HTTP processing. But the Go language is very different in this respect, and its standard library is very powerful. If you think the Go standard library is not powerful enough to do what you want to do, then I say you are wrong. The Go language standard library is incredibly powerful, and it's worth taking the time to read its code and learn the patterns it implements.
Func (srv * Server) ListenAndServe () error {addr: = srv.Addr if addr = "" {addr = ": http"} ln, err: = net.Listen ("tcp", addr) if err! = nil {return err} return srv.Serve (tcpKeepAliveListener {ln. (* net.TCPListener)})}
Fragments of ListenAndServe functions in the Go standard library. If you have written a Go program, you may have called this function many times, but have you ever taken the time to see its implementation? Click on the code snippet above.
The disillusionment in the trough of disillusionment comes from the fact that you are still thinking in other language patterns, and that you have not fully explored what Go has to offer you. Here are some fun things you can do to break down the dilemma and further explore the fun things in the language.
Go generate
Now take a look at go generate. Go generate is a command that you can use to automatically generate your own Go code. You can combine metaprogramming such as jsonenums, a class library used to automatically generate JSON marshalling boilerplate code for enumerated types, to use go generate to quickly and automatically repeat tedious code. There are already plenty of interfaces in the Go standard class library that can be used to parse AST, and AST makes it easier and easier to write metaprogramming tools. This was mentioned in two other discussions (metaprogramming practices in the Go language and embracing standard class libraries) at the meeting.
Func main () {flag.Parse () if len (* typeNames) = = 0 {log.Fatalf ("the flag-type must be set")} types: = strings.Split (* typeNames, ",") / / Only one directory ata time can be processed, and the default is ". Dir: "." If args: = flag.Args () Len (args) = = 1 {dir = args [0]} else if len (args) > 1 {log.Fatalf ("only one directory ata time")} pkg, err: = parser.ParsePackage (dir, * outputSuffix+ ".go") if err! = nil {log.Fatalf ("parsing package:% v") Err)} var analysis = struct {Command string PackageName string TypesAndValues map [string] [] string} {Command: strings.Join (os.Args [1:], "), PackageName: pkg.Name, TypesAndValues: make (map [string] [] string),} / / Run generate for each type. For _, typeName: = range types {values, err: = pkg.ValuesOfType (typeName) if err! = nil {log.Fatalf ("finding values for type% v:% v", typeName, err)} analysis.TypesAndValues [typeName] = values var buf bytes.Buffer if err: = generatedTmpl.Execute (& buf, analysis) Err! = nil {log.Fatalf ("generating code:% v", err)} src, err: = format.Source (buf.Bytes ()) if err! = nil {/ / Should never happen, but can arise when developing this code. / / The user can compile the output to see the error. Log.Printf ("warning: internal error: invalid Go generated:% s", err) log.Printf ("warning: compile the package to analyze the error") src = buf.Bytes ()} output: = strings.ToLower (typeName + * outputSuffix + ".go") outputPath: = filepath.Join (dir, output) if err: = ioutil.WriteFile (outputPath, src, 0644) Err! = nil {log.Fatalf ("writing output:% s", err)}
An interactive clip demonstrates how to write jsonenums commands.
OpenGL
Many people use Go as a web service, but did you know that you can also use Go to write very cool graphics applications? View the bundling of Go in OpenGL.
Func main () {glfw.SetErrorCallback (errorCallback) if! glfw.Init () {panic ("Can't init glfw!")} defer glfw.Terminate () window, err: = glfw.CreateWindow (Width, Height, Title, nil, nil) if err! = nil {panic (err)} window.MakeContextCurrent (1) gl.Init () if err: = initScene () Err! = nil {fmt.Fprintf (os.Stderr, "init:% s\ n", err) return} defer destroyScene () for! window.ShouldClose () {drawScene () window.SwapBuffers () glfw.PollEvents ()}}
Interactive clips show that OpenGL bundling of Go can make Gopher cube. Click the function or method name to explore.
Hackathon and Challenge
You can also watch challenges and hackathons, similar to Gopher Gala and Go Challenge. In the past, programmers from all over the world challenged some real cool projects, from which you could get inspiration.
The third stage: veteran
As a veteran, this means you can solve many of the problems you care about in the Go language. New problems that need to be solved will bring new questions, and through trial and error, you have learned what can be done and what cannot be done in the language. At this point, you have a solid understanding of the habits and patterns of the language. You can work very efficiently and write readable, well-documented, maintainable code.
A good way to become a veteran is to work on a big project. If you have an idea for a project, start working on it (of course you need to make sure it doesn't already exist). Most people may not have the idea of a big project, so they can contribute to existing projects. The Go language already has many large projects, and they are being widely used, such as Docker, Kubernetes, and Go itself. You can take a look at this project list.
Func (cli * DockerCli) CmdRestart (args... string) error {cmd: = cli.Subcmd ("restart", "CONTAINER [CONTAINER...]", "Restart a running container", true) nSeconds: = cmd.Int ([] string {"t", "- time"}, 10, "Seconds to wait for stop before killing the container.") Cmd.Require (flag.Min, 1) utils.ParseFlags (cmd, args, true) v: = url.Values {} v.Set ("t", strconv.Itoa (* nSeconds)) var encounteredError error for _, name: = range cmd.Args () {_, err: = readBody (cli.call ("POST", "/ containers/" + name+ "/ restart?" + v.Encode (), nil False) if err! = nil {fmt.Fprintf (cli.err, "% s\ n", err) encounteredError = fmt.Errorf ("Error: failed to restart one or more containers")} else {fmt.Fprintf (cli.out, "% s\ n", name)}} return encounteredError}
An interactive code snippet for the Docker project. Click on the name of the function to begin the journey of exploration.
Veterans should have a strong grasp of the tools of the Go ecosystem, because they really improve productivity. You should know go generate,go vet,go test-race and gofmt/goimports/goreturns. You should use go fmt because it automatically formats your code according to the style standards of the Go community. Goimports can do the same thing and add missing imports. Goretures not only does what I said earlier, but also adds missing errors to the return expression, which is a nuisance to everyone.
In the veteran stage, you must start doing code review. The point of code review is not to fix or find errors (that's what testers do). Code review can help maintain a uniform programming style, improve the overall quality of the software, and improve your own programming skills in the feedback of others. Almost all large open source projects code review every submission.
Here's an example of learning from human feedback: Google's Go team used to declare command-line tags outside the main function. At last year's GopherCon conference, Francesc met Peter Bourgon (@ peterbourgon) from SoundCloud. Peter Bourgon says that at SoundCloud, they all declare tags inside the main function so that they don't mistakenly use tags outside. Francesc now considers this to be a best practice.
Stage IV: experts
As an expert, you have a good understanding of the philosophy of language. For the features of Go, you know when to use it and when not to use it. For example, Jeremy Saenz talked about when interfaces should not be used in the dotGo Storm discussion.
Func (client * Client) Go (serviceMethod string, args interface {}, reply interface {}, done chan * Call) * Call {call: = new (Call) call.ServiceMethod = serviceMethod call.Args = args call.Reply = reply if done = nil {done = make (chan * Call, 10) / / buffered. } else {/ / If caller passes done! = nil, it must arrange that / / done has enough buffer for the number of simultaneous / / RPCs that will be using that channel. If the channel / / is totally unbuffered, it's best not to run at all. If cap (done) = 0 {log.Panic ("rpc: done channel is unbuffered")}} call.Done = done client.send (call) return call}
A small piece of interactive code from the standard class library uses the channel. Understanding the decision behind the patterns in the standard class library is the only way to become an expert.
But don't be an expert limited to a single language. Like any other language, Go is just a tool. You should also explore other languages and learn their patterns and styles. Francesc found inspiration for writing JavaScript from his experience with Go. He also likes the Haskell language, which focuses on immutability and is committed to avoiding variability, and gets inspiration for how to write Go code.
Preacher
As a preacher, you share your knowledge and teach what you have learned and the best practices you propose. You can share what you like or dislike about Go. There are Go meetings all over the world. Find the one closest to you.
You can be a preacher at any stage, and don't wait until you become an expert in the field to make your voice heard. At any stage of your Go study, ask questions, give feedback based on your experience, and don't be shy about asking what you don't like. The feedback you provide can help the community improve the way it does things, or it may change the way you think about programming.
Func main () {httpAddr: = flag.String ("http", "127.0.0.1 flag.StringVar 3999", "HTTP service address (e.g., '127.0.0.1 http 3999')") originHost: = flag.String ("orighost", "", "host component of web origin URL (e.g.,' localhost')") flag.StringVar (& basePath, "base", "" "base path for slide template and static resources") flag.BoolVar (& present.PlayEnabled, "play", true, "enable playground (permit execution of arbitrary user code)") nativeClient: = flag.Bool ("nacl", false, "use Native Client environment playground (prevents non-Go code execution)") flag.Parse () if basePath = "" {p, err: = build.Default.Import (basePkg, ") Build.FindOnly) if err! = nil {fmt.Fprintf (os.Stderr, "Couldn't find gopresent files:% v\ n", err) fmt.Fprintf (os.Stderr, basePathMessage, basePkg) os.Exit (1)} basePath = p.Dir} err: = initTemplates (basePath) if err! = nil {log.Fatalf ("Failed to parse templates:% v") Err)} ln, err: = net.Listen ("tcp", * httpAddr) if err! = nil {log.Fatal (err)} defer ln.Close (), port Err: = net.SplitHostPort (ln.Addr (). String ()) if err! = nil {log.Fatal (err)} origin: = & url.URL {Scheme: "http"} if * originHost! = "" {origin.Host = net.JoinHostPort (* originHost, port)} else if ln.Addr (). (* net.TCPAddr). IP.IsUnspecified () {name _: = os.Hostname () origin.Host = net.JoinHostPort (name, port)} else {reqHost, reqPort, err: = net.SplitHostPort (* httpAddr) if err! = nil {log.Fatal (err)} if reqPort = = "0" {origin.Host = net.JoinHostPort (reqHost Port)} else {origin.Host = * httpAddr}} if present.PlayEnabled {if * nativeClient {socket.RunScripts = false socket.Environ = func () [] string {if runtime.GOARCH = = "amd64" {return environ ("GOOS=nacl") "GOARCH=amd64p32")} return environ ("GOOS=nacl")}} playScript (basePath, "SocketTransport") http.Handle ("/ socket", socket.NewHandler (origin))} http.Handle ("/ static/") Http.FileServer (http.Dir (basePath)) if! ln.Addr (). IP.IsLoopback () & & present.PlayEnabled &! * nativeClient {log.Print (localhostWarning)} log.Printf ("Open your web browser and visit% s", origin.String ()) log.Fatal (http.Serve (ln, nil))
The popular main function of the present command, which is used by many Go users to make slides. Many speakers have modified this module to meet their needs.
Quan A
Q: one of the features I miss in the go language is a good debugger.
A: we are working on it, not just the debugger, but we will also provide a better overall monitoring tool that gives you better insight into what the program is doing while it is running (showing the status of all running goroutine). Explore it in GO 1.5.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 249
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.