The Go Language command source file

Source: Internet
Author: User
> Editor's note > ###### * Hello everyone, I am it, I opened a column on the Geek Time "[Go language core 36 speak] (https://time.geekbang.org/column/intro/112?utm_source= website&utm_medium=goyuyanzhongwenwang&utm_campaign=112-presell&utm_content=link0814) ", will be more than 10 years to Go The actual combat experience of the language and experiences are recorded in this column, thank you all the previous time on my health concerns, the current surgery is completed, is a long period of recuperation, I also hope that through the rest of the time to the precipitation and share more technical knowledge, thank you for your support and concern ~! * We already know that the environment variable ' Gopath ' points to one or more workspaces, and each workspace has a source code file that is the basic form of the package. Here the source file is divided into three kinds, namely: command source files, library source code files and test source files, they have different uses and write rules. Once you start learning to write programs in a programming language, we want to get feedback in the process of coding in a timely manner so that we know the right and wrong. In fact, our effective learning and progress is achieved through constant acceptance of feedback and implementation of corrections. For the go language, you will always write programs that can run directly during the learning phase. To this day, I will still use this method if I want to do some experiments. This will certainly involve the writing of command source files, and command source files can be easily launched with the ' Go Run ' command. * * Question: What is the purpose of the command source file and how to write it? Typical answer * * The command source file is the running portal of the program, which must be owned by each program that can run independently. We can build or install the executable file corresponding to it, which will generally have the same name as the direct parent directory of the command source file. If a source file declaration belongs to the ' main ' package, and contains a parameterless declaration without a result declaration of ' main ' function, then is the command source file. Just like this: "Package Mainimport" FMT "Func Main () {FMT. Println ("Hello, world!")} "If you save this code as a demo1.go file, you will see ' Hello, world! ' in the screen (standard output) after running the ' Go Run demo1.go ' command. When modular programming is required, we tend to split the code into multiple files and even split into different code packages. But anyway, for an independent program toSaid command source files will always only have one. If there is a source code file with the command source files, then they should also be declared to belong to the ' main ' package. * * Problem Resolution * * Command source file is so important that it has undoubtedly become our first assistant to learn the go language. However, will only print ' Hello, world! ' is not enough, we must not be "Hello, World" party. Now that you've decided to learn the go language, you should go deep into every point of knowledge. Whether it's Linux or Windows, if you've ever used a command line, you'll know that almost all commands are acceptable parameters (argument). Executable files generated by building or installing command source files can be considered "commands" and, since they are commands, they should have the ability to receive parameters. Below, I'll take you through a series of questions about the reception and parsing of command parameters. * * Knowledge Extension ****1 command source file How to receive parameters * * First look at an incomplete code: "The Package mainimport (//need to add code here.) [1] "FMT") var name stringfunc init () {//need to add code here. [2]} Func Main () {///need to add code here. [3]fmt. Printf ("Hello,%s!\n", name)} "If I want you to help me add the appropriate code to the comment and have the program implement the" greet someone according to the parameters given when running the program ", what are you going to do? If you know what to do, try to implement it now. If you don't know and don't worry, let's take care of it together. First, there is a code package in the Go Language standard library dedicated to receiving and parsing command parameters. This code package is named ' Flag '. As I said before, if you want to use the program entities in a package in your code, you should pilot this package. Therefore, we need to add the code ' flag ' at ' [1] '. Note that this should be preceded by an English half-width quotation mark before and after the Code package import path. As a result, the above code imports both the ' flag ' and ' FMT ' packages. Second, a person's name is definitely represented by a string. So we're going to add the code for the ' Stringvar ' function that calls the ' flag ' package at ' [2] '. Just like this: "Flag." Stringvar (&name, "name", "Everyone", "the Greeting object.") "' function ' flag. Stringvar ' accepts 4 parameters. The 1th parameter is the address of the value that is used to store the command parameter, specifically, the variable ' na ' that was declared earlierThe address of me ', denoted by the expression ' &name '. The 2nd parameter is to specify the name of the command parameter, here is ' name '. The 3rd parameter is to specify the default value when the command parameter is not appended, and here is ' everyone '. As for the 4th function parameter, this is a short description of the command argument, which is used when printing the command description. By the way, there is one with ' flag '. Stringvar ' function is similar to a function called ' flag '. String '. The difference between these two functions is that the latter directly returns an address that has been allocated to store the command parameter values. If we use it, we need to change the name "var" to "var name = flag." String ("name", "Everyone", "the Greeting object.") "So, if we use ' flag '. The String ' function needs to change the original code. This does not meet the requirements of the above questions. Say the last one in the blanks. We need to add code ' flag ' at ' [3] '. Parse () '. function ' flag. Parse ' is used to really parse the command arguments and assign their values to the corresponding variables. The call to the function must be declared on all command parameters storage vectors (here is the declaration of the variable ' name ') and set (here is the ' flag ' at ' [2] '). Stringvar ' function is called), and before any command parameter values are read. Because of this, we'd better put ' flag '. Parse () ' is placed on the first line of the function body of the ' main ' function. **2 How to run the command source file when the parameters, and how to see the use of parameters * * If we put the above code known as Demo2.go file, then run the following command to the parameter ' name ' value: ' Go run demo2.go-name= ' Robert "'    after running, print to standard output (STDOUT) content will be:" ' Hello, robert! ' "In addition, if you want to view the command source file parameter description, you can do:" "Go run Demo2.go --help ' $ ' indicates that we are running the ' Go Run ' command at the command prompt. The output after the run is similar to the following: "' Usage of/var/folders/ts/7lg_tl_x2gd_k1lm5g_48c7w0000gn/t/go-build155438482/b001/exe/demo2:  -name string    the Greeting object. (default "Everyone") Exit status 2 "' You might think '/var/folders/ts/7lg_tl_x2gd_k1lm5g_48c7w0000gn/t/go-build155438482/b001 /exe/demo2 ' is something. This is actually the full path of the executable file that was temporarily generated when the "Go Run" command was built to build the above command source file. If we first build this command source file and then run the generated executable, like this: "$ go build demo2.go$./demo2--help" Then the output will be "Usage of"./demo2: -name string& Nbsp;   the Greeting object. (default "Everyone") ' **3 how to customize the parameters of the command source file * * There are many ways to do this, and the simplest way is to use the variable ' flag '. Usage ' re-assigns values. ' Flag. The type of Usage ' is ' func () ', which is a function type with no parameter declaration and no result declaration. ' Flag. The Usage ' variable was already assigned at the time of declaration, so we were able to see the correct result when running the command ' go run demo2.go--help '. Attention, to ' flag. The assignment of the Usage ' must be in the call ' flag. Before the Parse ' function. Now, we save the Demo2.go as Demo3.go and add the following code at the beginning of the ' main ' function body. "Flag. Usage = func () { fmt. fprintf (OS. Stderr, "Usage of%s:\n", "question")  flag. Printdefaults ()} ' ' Then when run ' Go run demo3.go--help ', you will see ' Usage of Question: -name string     the Greeting object. (default "Everyone") Exit status 2 "Now go deeper and we are actually calling ' flag ' when we call some of the functions in the ' flag ' package (such as ' stringvar ', ' Parse ', and so on). CoThe corresponding method of the Mmandline ' variable. ' Flag.commandline ' is equivalent to the command parameter container by default. So, by re-assigning values to ' flag.commandline ', we can customize the parameters of the current command source file in a deeper way. Now let's put the pair ' flag ' in the ' main ' function body. The assignment statement for the Usage ' variable is written off, and then the following code is added at the beginning of the ' init ' function body: ' ' flag.commandline = flag. Newflagset ("", Flag. Exitonerror) Flag.CommandLine.Usage = func () {fmt. fprintf (OS. Stderr, "Usage of%s:\n", "question") flag. Printdefaults ()} ' runs the command ' go run demo3.go--help ' and its output is consistent with the last output. However, the latter method of customization is more flexible. For example, when we change the phrase "flag.commandline" to "Flag.commandline = flag." Newflagset ("", Flag. Paniconerror) ", then run the ' Go Run demo3.go--help ' command to produce another output effect. This is because we are passing it here to ' flag. The second parameter value of the Newflagset ' function is ' flag '. Paniconerror '. ' Flag. Paniconerror and ' flag. Exitonerror ' are constants that are predefined in the ' flag ' package. ' Flag. The meaning of Exitonerror ' is to tell the command parameter container to end the current program with the status code ' 2 ' after the command parameter is set with '--help ' or when the parameter is incorrect. The status code ' 2 ' represents the user incorrectly using the command, while ' flag '. The difference between Paniconerror ' and it is that at the end of the throw "run-time Panic (panic)". Both of these situations will call ' flag ' on us. Parse ' function is triggered. By the way, "run-time Panic" is the concept of Go program error handling. I'll talk about how it's thrown and recovered in the next section of this column. Further down, we simply do not use the global ' flag.commandline ' variable and instead create a private command-parameter container ourselves. We add a variable declaration outside the function: ' var cmdline = flag. Newflagset ("qUestion ", Flag. Exitonerror) "And then we put the pair on ' flag. The call to Stringvar ' is replaced by a call to ' Cmdline.stringvar ' and then ' flag '. Parse () ' is replaced with ' Cmdline.parse (OS. Args[1:]) '. One of the ' OS. Args[1:] ' refers to the command parameters we have given. This is completely out of the ' flag.commandline '. ' *flag. Flagset ' type of variable ' cmdline ' has a lot of interesting methods. You can go and explore. I'm not here to tell you all about it. The benefit of doing so is still more flexible in customizing the command parameter container. But more importantly, your customizations will not affect the global variable ' flag.commandline ' at all. * * Summary * * Congratulations! You are now out of the first step of Go language programming. You can use go to write commands, and they can be used as many operating system commands, and can even embed them in various scripts. Although I have explained to you the basic method of writing the command source file, and also talked about the various preparations needed to get it to accept parameters, this is not all. Don't worry, I'll always mention it in the back. In addition, if you want to learn more about the use of the ' flag ' package, you can check the documentation at [this URL] (https://golang.google.cn/pkg/flag/). Or launch a Go language document server locally using the ' godoc ' command. How do I use the ' godoc ' command? You can see [here] (HTTPS://GITHUB.COM/HYPER0X/GO_COMMAND_TUTORIAL/BLOB/MASTER/0.5.MD). * * Study Questions * * We've seen the way to give the command source file a string type parameter value, can you pass in something else? This is the study questions I left today. 1. By default, what types of parameter values can we accept for the command source file? 2. Can we use a custom data type as the type of the parameter value? If so, what do you do? You can get the answer to the first question by reviewing the document. Keep in mind that quickly viewing and understanding documents is a must-have skill. As for the second question, it may be difficult to answer because it involves another question: "How do you declare your data type?" "(That's the question I'll cover in the next section of the column too). If so, I would like you to take note of it and the other issue here, and answer the former before you can solve the latter. [You can also click the text link or scan the QR code below to subscribe to my column to discuss with me. ] (https://time.geekbang.org/column/Intro/112?utm_source=website&utm_medium=goyuyanzhongwenwang&utm_campaign=112-presell&utm_content= link0814) Limited Time Benefits: 1, scan the poster QR code, you can reduce 6 yuan, equivalent to 39 yuan subscription; 2, after the subscription column, through the exclusive sharing poster QR code, each invite a friend, you can get 12 yuan cash rebate, withdrawal method (Geek time app-My-share a reward)! [Go Language Chinese network 1.jpg] (https://static.studygolang.com/180814/3aa8f148cc3097962d38f253998de964.jpg) 450 reads  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.