From 02ef8fa5ddb8111aa8752ffb8267e67c4e209649 Mon Sep 17 00:00:00 2001 From: Steve Traut Date: Mon, 1 Mar 2021 10:42:43 -0500 Subject: _content/doc: fix module and tutorial bugs and clean up flow For golang/go#44241 - Fix issues 2, 3, 8, 16, 17, 18 from golang/go#44241 Other changes in multiple topics: - In markdown, replace HTML anchor tags with {#anchor} tags. - In a few places, add content to clarify that module path must be a location from which the module can be downloaded. - Where it was missing, add example.com domain to example module paths. Hopefully, this will reinforce the idea that the module path should typically include a domain. Docs will use something that looks like a domain name for module path. - Add more cross-references from tutorial to references for packages and commands. - Rewrite a few links so that they include the topic title, rather than simply inline text. Left those links whose destinations are references -- the item's name seems to suggest that a reference is at the destination. - Remove domain name from golang.org doc links, leaving root directory. Such as /cmd/go/* or /doc/modules/* - Add path up to root for all links in the same domain. Some were linking by file name only. - Change standard library links from golang.org to pkg.go.dev. Changes in the module tutorial: - Add text to help clarify that there should be a hello and greetings directory as siblings in their directory hierarchy. Some users thought one should be subordinate to the other. - Where needed, reorder steps so that `go mod init` is run before code is added. This is intended to reinforce the importance of the module's presence. - In require/replace steps, have the user use `go mod edit` rather than editing the go.mod file in an editor. The tools are more likely to yield a functioning result. - Where possible/appropriate, change module directive link destinations from "Modules reference" to go.mod reference. - Change "run the code" steps so that they all use `go run .` rather than `go build` or `go run `. This removes the impedance of explanation and more commands, while moving the explanation of `go build` and `go install` to a separate topic where they share a clearer context. - Add a "Conclusion" topic with a few links. The tutorial ended rather abruptly before. - Minor edits to remove some redundant language. Change-Id: I93055035d73c362ba73edea458fc53bc45e66512 Reviewed-on: https://go-review.googlesource.com/c/website/+/297531 Trust: Steve Traut Run-TryBot: Steve Traut TryBot-Result: Go Bot Reviewed-by: Jay Conrod --- _content/doc/tutorial/add-a-test.html | 42 ++-- _content/doc/tutorial/call-module-code.html | 224 +++++++++++---------- _content/doc/tutorial/compile-install.html | 124 ++++++++---- _content/doc/tutorial/create-module.html | 81 ++++---- _content/doc/tutorial/getting-started.html | 48 +++-- .../doc/tutorial/greetings-multiple-people.html | 71 +++---- _content/doc/tutorial/handle-errors.html | 29 +-- _content/doc/tutorial/index.html | 7 +- _content/doc/tutorial/module-conclusion.html | 31 +++ _content/doc/tutorial/random-greeting.html | 101 ++++++---- 10 files changed, 433 insertions(+), 325 deletions(-) create mode 100644 _content/doc/tutorial/module-conclusion.html (limited to '_content/doc/tutorial') diff --git a/_content/doc/tutorial/add-a-test.html b/_content/doc/tutorial/add-a-test.html index d52f3d3b..dffd4924 100644 --- a/_content/doc/tutorial/add-a-test.html +++ b/_content/doc/tutorial/add-a-test.html @@ -12,7 +12,7 @@

@@ -73,16 +73,13 @@ func TestHelloEmpty(t *testing.T) { Implement test functions in the same package as the code you're testing.

  • - Create two test functions to test the - greetings.Hello function. Test function names have the form - TestName, where Name is specific to the test. Also, test functions - take a pointer to the - testing package's - testing.T as a parameter. You use this parameter's methods - for reporting and logging from your test. + Create two test functions to test the greetings.Hello + function. Test function names have the form TestName, + where Name says something about the specific test. Also, test + functions take a pointer to the testing package's + testing.T + type as a parameter. You use this parameter's methods for reporting + and logging from your test.
  • Implement two tests: @@ -94,18 +91,16 @@ func TestHelloEmpty(t *testing.T) { able to return a valid response message. If the call returns an error or an unexpected response message (one that doesn't include the name you passed in), you use the t parameter's - Fatalf method to print a message to the console and end - execution. + + Fatalf method to print a message to the console + and end execution.
  • TestHelloEmpty calls the Hello function with an empty string. This test is designed to confirm that your error handling works. If the call returns a non-empty string or no - error, you use the t parameter's - Fatalf method - to print a message to the console and end execution. + error, you use the t parameter's Fatalf + method to print a message to the console and end execution.
  • @@ -114,7 +109,7 @@ func TestHelloEmpty(t *testing.T) {
  • At the command line in the greetings directory, run the - go test command to execute the test. @@ -202,16 +197,15 @@ FAIL example.com/greetings 0.182s

    - This topic introduced Go's built-in support for unit testing. In the - tutorial's next topic, you'll see how to - compile and install your code to run it locally. + In the next (and last) topic, you'll see how to compile and install your code + to run it locally.

    diff --git a/_content/doc/tutorial/call-module-code.html b/_content/doc/tutorial/call-module-code.html index 3c3602b8..bce43d72 100644 --- a/_content/doc/tutorial/call-module-code.html +++ b/_content/doc/tutorial/call-module-code.html @@ -4,7 +4,7 @@ }-->

    - In the previous section, you created a + In the previous section, you created a greetings module. In this section, you'll write code to make calls to the Hello function in the module you just wrote. You'll write code you can execute as an application, and which calls code in the @@ -13,7 +13,7 @@

      @@ -22,8 +22,16 @@ is where you'll write your caller.

      - For example, if your current directory in the command prompt is the - greetings directory, you could use the following commands: + After you create this directory, you should have both a hello and a + greetings directory at the same level in the hierarchy, like so: +

      +
      <home>/
      + |-- greetings/
      + |-- hello/
      + +

      + For example, if your command prompt is in the greetings directory, you + could use the following commands:

      @@ -35,7 +43,28 @@ cd hello
         
       
         
    1. - In your text editor (in the hello directory), create a file in which to + Enable dependency tracking for the code you're about to write. + +

      + To enable dependency tracking for your code, run the + go mod init command, giving it the name of the module + your code will be in.

      + +

      + For the purposes of this tutorial, use example.com/hello + for the module path. +

      + +
      +$ go mod init example.com/hello
      +go: creating new go.mod: module example.com/hello
      +
      +
    2. + +
    3. + In your text editor, in the hello directory, create a file in which to write your code and call it hello.go.
    4. @@ -61,8 +90,7 @@ func main() { message := greetings.Hello("Gladys") fmt.Println(message) } -
      +

      In this code, you: @@ -71,16 +99,16 @@ func main() {

      • Declare a main package. In Go, code executed as an - application must go in a main package. + application must be in a main package.
      • Import two packages: example.com/greetings and - fmt. This gives your code access to functions in those - packages. Importing example.com/greetings (the package - contained in the module you created earlier) gives you access to the - Hello function. You also import fmt, with - functions for handling input and output text (such as printing text to - the console). + the fmt package. This + gives your code access to functions in those packages. Importing + example.com/greetings (the package contained in the module + you created earlier) gives you access to the Hello + function. You also import fmt, with functions for handling + input and output text (such as printing text to the console).
      • Get a greeting by calling the greetings package’s @@ -90,148 +118,124 @@ func main() {
      • - Create a new module for this hello package. + Edit the example.com/hello module to use your local + example.com/greetings module.

        - From the command line at the hello directory, run the - go mod init command, giving it the name of the module your - code will be in (here, just use "hello"). -

        - -
        -$ go mod init hello
        -go: creating new go.mod: module hello
        -
        -
      • - -
      • - Edit the hello module to use the unpublished greetings module. - -

        - For production use, you’d publish your modules on a server, either inside - your company or on the internet, and the Go command will download them - from there. For now, you need to adapt the caller's module so it can find - the greetings code on your local file system. + For production use, you’d publish the example.com/greetings + module from its repository (with a module path that reflected its published + location), where Go tools could find it to download it. + For now, because you haven't published the module yet, you need to adapt + the example.com/hello module so it can find the + example.com/greetings code on your local file system.

        - To do that, make a small change to hello module’s go.mod - file. + To do that, use the + go + mod edit command to edit the example.com/hello + module to redirect Go tools from its module path (where the module isn't) + to the local directory (where it is).

        1. - In the hello directory, open the go.mod file, change it so that it looks - like the following, and save the file. + From the command prompt in the hello directory, run the following + command: + +
          +$ go mod edit -replace=example.com/greetings=../greetings
          +
          + +

          + The command specifies that example.com/greetings should be + replaced with ../greetings for the purpose of locating the + dependency. After you run the command, the go.mod file in the hello + directory should include a + replace directive: +

          -module hello
          +module example.com/hello
           
          -go 1.14
          +go 1.16
           
           replace example.com/greetings => ../greetings
           
          - -

          - Here, the - - replace directive - - tells Go to replace the module path (the URL - example.com/greetings) with a path you specify. In this - case, that's a greetings directory next to the hello directory. -

        2. - In the hello directory, run go build to make Go locate the - module and add it as a dependency to the go.mod file. + From the command prompt in the hello directory, run the + + go mod tidy command to synchronize the + example.com/hello module's dependencies, adding those + required by the code, but not yet tracked in the module. -
          -$ go build
          +        
          $ go mod tidy
           go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000
          -
          -
        3. - -
        4. - Look at go.mod again to see the changes made by go build, - including the require directive Go added. + +

          + After the command completes, the example.com/hello + module's go.mod file should look like this: +

          -
          -module hello
          +        
          module example.com/hello
           
          -go 1.14
          +go 1.16
           
           replace example.com/greetings => ../greetings
           
          -require example.com/greetings v0.0.0-00010101000000-000000000000
          -
          +require example.com/greetings v0.0.0-00010101000000-000000000000

          - To build the module, Go found the local code in the ../greetings - directory, then added a - - require directive - - to specify that hello is dependent on (requires) - example.com/greetings. You created this dependency when - you imported the greetings package (contained in the - greetings module) in hello.go. The replace directive - tells Go where to find the greetings module, because it - isn't published yet. + The command found the local code in the greetings directory, then + added a require + directive to specify that example.com/hello + requires example.com/greetings. You created this + dependency when you imported the greetings package in + hello.go. +

          +

          + The number following the module path is a pseudo-version number + -- a generated number used in place of a semantic version number (which + the module doesn't have yet).

          -

          - To reference a published module, a go.mod file would omit the - replace directive and use a - require directive with a tagged version number at the - end. + To reference a published module, a go.mod file would + typically omit the replace directive and use a + require directive with a tagged version number at the end.

          require example.com/greetings v1.1.0
          + +

          For more on version numbers, see + Module version numbering.

        -
      • -
      • - In the hello directory, run the hello executable - (created by go build) to confirm that the code works. -
          -
        • - On Linux or Mac: + At the command prompt in the hello directory, run your code to + confirm that it works. -
          -$ ./hello
          -Hi, Gladys. Welcome!
          -
          -
        • - -
        • - On Windows: - -
          -$ hello.exe
          +    
          +$ go run .
           Hi, Gladys. Welcome!
          -
          -
        • -
        +

    - Congrats! You've written two functioning modules. In the tutorial's - next topic, you'll add some error handling. + Congrats! You've written two functioning modules. +

    + +

    + In the next topic, you'll add some error handling.

    diff --git a/_content/doc/tutorial/compile-install.html b/_content/doc/tutorial/compile-install.html index 5395ae51..4d596185 100644 --- a/_content/doc/tutorial/compile-install.html +++ b/_content/doc/tutorial/compile-install.html @@ -4,17 +4,27 @@ }-->

    - In the last section, you'll learn a new go command. While the - go run command is a useful shortcut for compiling and running a - single-file program, it doesn't generate a binary executable you can easily - run again. If you want one of those, a good choice is to run the - go install command, which compiles your code and installs the resulting binary executable where - you can run it. + In this last topic, you'll learn a couple new go commands. While + the go run command is a useful shortcut for compiling and running + a program when you're making frequent changes, it doesn't generate a binary + executable.

    + +

    + This topic introduces two additional commands for building code:

    +
      +
    • + The go + build command compiles the packages, along with their dependencies, + but it doesn't install the results. +
    • +
    • + The go + install command compiles and installs the packages. +
    • +
    +
  • - Call your code from another module -- + Call your code from another module -- Import and use your new module.
  • - Return and handle an error -- Add simple + Return and handle an error -- Add simple error handling.
  • - Return a random greeting -- Handle data + Return a random greeting -- Handle data in slices (Go's dynamically-sized arrays).
  • - Return greetings for multiple people -- Store key/value pairs in a map.
  • - Add a test -- Use Go's built-in unit testing + Add a test -- Use Go's built-in unit testing features to test your code.
  • - Compile and install the application -- + Compile and install the application -- Compile and install your code locally.
  • Prerequisites

    @@ -81,18 +81,18 @@

    Start a module that others can use

    - Start by creating a - Go module. In a + Start by creating a Go module. In a module, you collect one or more related packages for a discrete and useful set of functions. For example, you might create a module with packages that have functions for doing financial analysis so that others writing financial - applications can use your work. + applications can use your work. For more about developing modules, see + Developing and publishing modules.

    Go code is grouped into packages, and packages are grouped into modules. Your - package's module specifies the context Go needs to run the code, including the - Go version the code is written for and the set of other modules it requires. + module specifies dependencies needed to run your code, including the Go + version and the set of other modules it requires.

    @@ -127,7 +127,6 @@ cd %HOMEPATH%

  • Create a greetings directory for your Go module source code. - This is where you'll write your module code.

    For example, from your home directory use the following commands: @@ -143,16 +142,15 @@ cd greetings

  • Start your module using the go mod init command - to create a go.mod file. + >.

    - Run the go mod init command, giving it the path of the module - your code will be in. Here, use example.com/greetings for the - module path -- in production code, this would be the URL from which your - module can be downloaded. + Run the go mod init command, giving it your module path -- + here, use example.com/greetings. If you publish a module, + this must be a path from which your module can be downloaded by + Go tools. That would be your code's repository.

    @@ -162,13 +160,12 @@ go: creating new go.mod: module example.com/greetings
         >
     
         

    - The go mod init command creates a go.mod file that identifies - your code as a module that might be used from other code. The file you - just created includes only the name of your module and the Go version your - code supports. But as you add dependencies -- meaning packages from other - modules -- the go.mod file will list the specific module versions to use. - This keeps builds reproducible and gives you direct control over which - module versions to use. + The go mod init command creates a go.mod file to track your + code's dependencies. So far, the file includes only the name of your + module and the Go version your code supports. But as you add dependencies, + the go.mod file will list the versions your code depends on. This keeps + builds reproducible and gives you direct control over which module + versions to use.

  • @@ -212,10 +209,12 @@ func Hello(name string) string { Implement a Hello function to return the greeting.

    This function takes a name parameter whose type is - string, and returns a string. In Go, a - function whose name starts with a capital letter can be called by a - function not in the same package. This is known in Go as an - exported name. + string. The function also returns a string. + In Go, a function whose name starts with a capital letter can be + called by a function not in the same package. This is known in Go as + an exported name. For more about exported names, see + Exported names in the + Go tour.

    @@ -236,11 +235,12 @@ message = fmt.Sprintf("Hi, %v. Welcome!", name)
  • - Use the fmt package's Sprintf function to - create a greeting message. The first argument is a format string, and - Sprintf substitutes the name parameter's value - for the %v format verb. Inserting the value of the - name parameter completes the greeting text. + Use the fmt package's + Sprintf function to create a greeting message. The + first argument is a format string, and Sprintf substitutes + the name parameter's value for the %v format + verb. Inserting the value of the name parameter completes + the greeting text.
  • Return the formatted greeting text to the caller.
  • @@ -248,12 +248,11 @@ message = fmt.Sprintf("Hi, %v. Welcome!", name)

    - In the next step, you'll call this - function from another module. + In the next step, you'll call this function from another module.

    diff --git a/_content/doc/tutorial/getting-started.html b/_content/doc/tutorial/getting-started.html index fc05867f..eff1bb69 100644 --- a/_content/doc/tutorial/getting-started.html +++ b/_content/doc/tutorial/getting-started.html @@ -21,7 +21,7 @@

    Prerequisites

    @@ -90,26 +90,35 @@ cd hello
  • - Initialize a new module for tracking dependencies. + Enable dependency tracking for your code.

    - When your code imports packages from another module, a go.mod file lists - the specific modules and versions providing those packages. That file - stays with your code, including in your source code repository. + When your code imports packages contained in other modules, you manage + those dependencies through your code's own module. That module is defined + by a go.mod file that tracks the modules that provide those packages. That + go.mod file stays with your code, including in your source code + repository.

    - To create a go.mod file, run the - go mod init command, giving it the name of the module your code will be in (here, just use - "hello"): + To enable dependency tracking for your code by creating a go.mod file, run + the + go mod init command, + giving it the name of the module your code will be in. The name is the + module's module path. In most cases, this will be the repository + location where your source code will be kept, such as + github.com/mymodule. If you plan to publish your module + for others to use, the module path must be a location from + which Go tools can download your module. +

    + +

    For the purposes of this tutorial, just use + example.com/hello.

    -$ go mod init hello
    -go: creating new go.mod: module hello
    +$ go mod init example.com/hello
    +go: creating new go.mod: module example.com/hello
     
  • @@ -143,10 +152,10 @@ func main() {
  • Import the popular - fmt package, + fmt package, which contains functions for formatting text, including printing to the console. This package is one of the - standard library packages you got + standard library packages you got when you installed Go.
  • @@ -168,7 +177,7 @@ Hello, World!

    The - go run command is one of many go commands you'll use to get things done with @@ -252,7 +261,10 @@ func main() { Add new module requirements and sums.

    - Go will add the quote module as a requirement, as well as a go.sum file for use in authenticating the module. For more, see Module authentication using go.sum. + Go will add the quote module as a requirement, as well as a + go.sum file for use in authenticating the module. For more, see + Authenticating modules in the Go + Modules Reference.

     $ go mod tidy
    @@ -289,5 +301,5 @@ Don't communicate by sharing memory, share memory by communicating.
     

    With this quick introduction, you got Go installed and learned some of the basics. To write some more code with another tutorial, take a look at - Create a Go module. + Create a Go module.

    diff --git a/_content/doc/tutorial/greetings-multiple-people.html b/_content/doc/tutorial/greetings-multiple-people.html index 8100c080..1d83192d 100644 --- a/_content/doc/tutorial/greetings-multiple-people.html +++ b/_content/doc/tutorial/greetings-multiple-people.html @@ -6,33 +6,27 @@

    In the last changes you'll make to your module's code, you'll add support for getting greetings for multiple people in one request. In other words, you'll - handle a multiple-value input and pair values with a multiple-value output. + handle a multiple-value input, then pair values in that input with a + multiple-value output. To do this, you'll need to pass a set of names to a + function that can return a greeting for each of them.

    - To do this, you'll need to pass a set of names to a function that can return a - greeting for each of them. Changing the Hello function's - parameter from a single name to a set of names would change the function - signature. If you had already published the greetings module and - users had already written code calling Hello, that change would - break their programs. In this situation, a better choice is to give new - functionality a new name. -

    + But there's a hitch. Changing the Hello function's + parameter from a single name to a set of names would change the function's + signature. If you had already published the example.com/greetings + module and users had already written code calling Hello, that + change would break their programs.

    - In the last code you'll add with this tutorial, update the code as if you've - already published a version of the greetings module. Instead of - changing the Hello function, add a new function - Hellos that takes a set of names. Then, for the sake of - simplicity, have the new function call the existing one. Keeping both - functions in the package leaves the original for existing callers (or future - callers who only need one greeting) and adds a new one for callers that want - the expanded functionality. + In this situation, a better choice is to write a new function with a different + name. The new function will take multiple parameters. That preserves the old + function for backward compatibility.

      @@ -111,27 +105,28 @@ func randomFormat() string { mapped to greeting messages.
    1. - Have the new Hellos function call the existing Hello function. This - leaves both functions in place. + Have the new Hellos function call the existing + Hello function. This helps reduce duplication while also + leaving both functions in place.
    2. - Create a messages - map to associate each of the + Create a messages map to associate each of the received names (as a key) with a generated message (as a value). In Go, you initialize a map with the following syntax: make(map[key-type]value-type). You have - the Hellos function return this map to the caller. + the Hellos function return this map to the caller. For more + about maps, see Go maps in + action on the Go blog.
    3. Loop through the names your function received, checking that each has a non-empty value, then associate a message with each. In this for loop, range returns two values: the index of the current item in the loop and a copy of the item's value. You - don't need the index, so you use the Go - blank identifier (an underscore) - to ignore it. + don't need the index, so you use the Go blank identifier (an underscore) + to ignore it. For more, see + The blank + identifier in Effective Go.
    4. @@ -193,7 +188,7 @@ func main() {
    5. At the command line, change to the directory that contains hello/hello.go, - then run hello.go to confirm that the code works. + then use go run to confirm that the code works.

      The output should be a string representation of the map associating names @@ -201,7 +196,7 @@ func main() {

      -$ go run hello.go
      +$ go run .
       map[Darrin:Hail, Darrin! Well met! Gladys:Hi, Gladys. Welcome! Samantha:Hail, Samantha! Well met!]
       
      @@ -210,18 +205,18 @@ map[Darrin:Hail, Darrin! Well met! Gladys:Hi, Gladys. Welcome! Samantha:Hail, Sa

      This topic introduced maps for representing name/value pairs. It also - introduced the idea of - preserving backward compatibility + introduced the idea of preserving backward compatibility by implementing a new function for new or changed functionality in a module. - In the tutorial's next topic, you'll use - built-in features to create a unit test for your code. + For more about backward compatibility, see + Keeping your modules + compatible.

      +

      Next, you'll use built-in Go features to create a unit test for your code.

      + diff --git a/_content/doc/tutorial/handle-errors.html b/_content/doc/tutorial/handle-errors.html index 4dfd4b13..76f7a4f3 100644 --- a/_content/doc/tutorial/handle-errors.html +++ b/_content/doc/tutorial/handle-errors.html @@ -11,7 +11,7 @@
        @@ -55,14 +55,13 @@ func Hello(name string) (string, error) { Change the function so that it returns two values: a string and an error. Your caller will check the second value to see if an error occurred. (Any Go function can - return multiple values.) + return multiple values. For more, see + Effective Go.)
      1. Import the Go standard library errors package so you can use its - errors.New function.
      2. @@ -106,7 +105,7 @@ func main() { log.SetFlags(0) // Request a greeting message. - message, err := greetings.Hello("") + message, err := greetings.Hello("") // If an error was returned, print it to the console and // exit the program. if err != nil { @@ -126,7 +125,7 @@ func main() {
        • Configure the - log package to + log package to print the command name ("greetings: ") at the start of its log messages, without a time stamp or source file information.
        • @@ -163,7 +162,7 @@ func main() {

          -$ go run hello.go
          +$ go run .
           greetings: empty name
           exit status 1
           

          - That's essentially how error handling in Go works: Return an error as a value - so the caller can check for it. It's pretty simple. In the tutorial's - next topic, you'll use a Go slice to return - a randomly-selected greeting. + That's common error handling in Go: Return an error as a value so the caller + can check for it. +

          + +

          + Next, you'll use a Go slice to return a randomly-selected greeting.

          diff --git a/_content/doc/tutorial/index.html b/_content/doc/tutorial/index.html index 80f9c018..1bbb78d0 100644 --- a/_content/doc/tutorial/index.html +++ b/_content/doc/tutorial/index.html @@ -20,13 +20,13 @@ - Getting started + Getting started Say Hello, World with Go. - Create a module + Create a module A multi-part tutorial that introduces common programming language @@ -38,7 +38,8 @@ A Tour of Go - An interactive introduction to Go: basic syntax and data structures; methods and interfaces; and Go's concurrency primitives. + An interactive introduction to Go: basic syntax and data structures; + methods and interfaces; and Go's concurrency primitives. diff --git a/_content/doc/tutorial/module-conclusion.html b/_content/doc/tutorial/module-conclusion.html new file mode 100644 index 00000000..f86af3af --- /dev/null +++ b/_content/doc/tutorial/module-conclusion.html @@ -0,0 +1,31 @@ + + +

          + In this tutorial, you wrote functions that you packaged into two modules: one + with logic for sending greetings; the other as a consumer for the first. +

          + + + +

          + For more on managing dependencies in your code, see + Managing dependencies. For + more about developing modules for others to use, see + Developing and publishing modules. +

          + +

          For many more features of the Go language, check out the + Tour of Go. +

          + + diff --git a/_content/doc/tutorial/random-greeting.html b/_content/doc/tutorial/random-greeting.html index d5a45be6..c6c8da72 100644 --- a/_content/doc/tutorial/random-greeting.html +++ b/_content/doc/tutorial/random-greeting.html @@ -10,15 +10,20 @@

          - To do this, you'll use a Go slice. A - slice is like an - array, except that it's dynamically sized as you add and remove items. It's - one of the most useful types in Go. You'll add a small slice to contain three - greeting messages, then have your code return one of the messages randomly. + To do this, you'll use a Go slice. A slice is like an array, except that its + size changes dynamically as you add and remove items. The slice is one of Go's + most useful types. +

          + +

          + You'll add a small slice to contain three greeting messages, then have your + code return one of the messages randomly. For more on slices, + see Go slices in the Go + blog.

            @@ -82,24 +87,22 @@ func randomFormat() string {
          1. In randomFormat, declare a formats slice with three message formats. When declaring a slice, you omit its size in the - brackets, like this: []string. This tells Go that the array - underlying a slice can be dynamically sized. + brackets, like this: []string. This tells Go that the size + of the array underlying the slice can be dynamically changed.
          2. Use the - math/rand package to generate a random number for selecting an item from the slice.
          3. - Add an - init function - to seed the rand package with the current time. Go executes - init functions automatically at program startup, after - global variables have been initialized. + Add an init function to seed the rand package + with the current time. Go executes init functions + automatically at program startup, after global variables have been + initialized. For more about init functions, see + Effective Go.
          4. In Hello, call the randomFormat function to @@ -109,48 +112,70 @@ func randomFormat() string {
          5. Return the message (or an error) as you did before.
        -

        - Your hello.go needn't change. -

      3. - At the command line, change to the hello directory, then run hello.go to - confirm that the code works. Run it multiple times, noticing that the - greeting changes. + In hello/hello.go, change your code so it looks like the following. -

        - Oh -- don't forget to add Gladys's name (or a different name, if you like) - as an argument to the Hello function call in hello.go: - greetings.Hello("Gladys") -

        +

        You're just adding Gladys's name (or a different name, if you like) + as an argument to the Hello function call in hello.go.

        + +
        package main
        +
        +import (
        +    "fmt"
        +    "log"
        +
        +    "example.com/greetings"
        +)
        +
        +func main() {
        +    // Set properties of the predefined Logger, including
        +    // the log entry prefix and a flag to disable printing
        +    // the time, source file, and line number.
        +    log.SetPrefix("greetings: ")
        +    log.SetFlags(0)
        +
        +    // Request a greeting message.
        +    message, err := greetings.Hello("Gladys")
        +    // If an error was returned, print it to the console and
        +    // exit the program.
        +    if err != nil {
        +        log.Fatal(err)
        +    }
        +
        +    // If no error was returned, print the returned message
        +    // to the console.
        +    fmt.Println(message)
        +}
        +
      4. + +
      5. + At the command line, in the hello directory, run hello.go to confirm that + the code works. Run it multiple times, noticing that the greeting changes.
        -$ go build
        -$ ./hello
        +$ go run .
         Great to see you, Gladys!
         
        -$ ./hello
        +$ go run .
         Hi, Gladys. Welcome!
         
        -$ ./hello
        +$ go run .
         Hail, Gladys! Well met!
        -
        +
  • - That's an introduction to a Go slice. To get even more use out of this type, - you'll use a slice to greet multiple people. That's in the tutorial's - next topic. + Next, you'll use a slice to greet multiple people.

    -- cgit v1.3-5-g9baa