One place for hosting & domains

      How To Write Your First Program in Go


      Introduction

      The “Hello, World!” program is a classic and time-honored tradition in computer programming. It’s a simple and complete first program for beginners, and it’s a good way to make sure your environment is properly configured.

      This tutorial will walk you through creating this program in Go. However, to make the program more interesting, you’ll modify the traditional “Hello, World!” program so that it asks the user for their name. You’ll then use the name in the greeting. When you’re done with the tutorial, you’ll have a program that looks like this when you run it:

      Output

      Please enter your name. Sammy Hello, Sammy! I'm Go!

      Prerequisites

      Before you begin this tutorial, you will need a local Go development environment set up on your computer. You can set this up by following one of these tutorials:

      Step 1 — Writing the Basic “Hello, World!” Program

      To write the “Hello, World!” program, open up a command-line text editor such as nano and create a new file:

      Once the text file opens up in the terminal window, you’ll type out your program:

      hello.go

      package main
      
      import "fmt"
      
      func main() {
        fmt.Println("Hello, World!")
      }
      

      Let’s break down the different components of the code.

      package is a Go keyword that defines which code bundle this file belongs to. There can be only one package per folder, and each .go file has to declare the same package name at the top of its file. In this example, the code belongs to the main package.

      import is a Go keyword that tells the Go compiler which other packages you want to use in this file. Here you import the fmt package that comes with the standard library. The fmt package provides formatting and printing functions that can be useful when developing.

      fmt.Println is a Go function, found in the fmt package, that tells the computer to print some text to the screen.

      You follow the fmt.Println function by a sequence of characters, like "Hello, World!", enclosed in quotation marks. Any characters that are inside of quotation marks are called a string. The fmt.Println function will print this string to the screen when the program runs.

      Save and exit nano by typing CTRL + X, when prompted to save the file, press Y.

      Now you can try your program.

      Step 2 — Running a Go Program

      With your “Hello, World!” program written, you're ready to run the program. You’ll use the go command, followed by the name of the file you just created.

      The program will execute and display this output:

      Output

      Hello, World!

      Let's explore what actually happened.

      Go programs need to compile before they run. When you call go run with the name of a file, in this case hello.go, the go command will compile the application and then run the resulting binary. For programs written in compiled programming languages, a compiler will take the code from a program and generate another type of lower-level code (such as source code or machine code) to produce an executable program.

      Go applications require a main package and exactly one main() function that serves as the entry point for the application. The main function takes no arguments and returns no values. Instead it tells the Go compiler that the package should be compiled as an executable package.

      Once compiled, the code executes by entering the main() function in the main package. It executes the line fmt.Println("Hello, World!") by calling the fmt.Println function. The string value of Hello, World! is then passed to the function. In this example, the string Hello, World! is also called an argument since it is a value that is passed to a method.

      The quotes that are on either side of Hello, World! are not printed to the screen because you use them to tell Go where your string begins and ends.

      In this step, you've created a working "Hello, World!" program with Go. In the next step, you will explore how to make the program more interactive.

      Step 3 — Prompting for User Input

      Every time you run your program, it produces the same output. In this step, you can add to your program to prompt the user for their name. You'll then use their name in the output.

      Instead of modifying your existing program, create a new program called greeting.go with the nano editor:

      First, add this code, which prompts the user to enter their name:

      greeting.go

      package main
      
      import (
          "fmt"
      )
      
      func main() {
        fmt.Println("Please enter your name.")
      }
      

      Once again, you use the fmt.Println function to print some text to the screen.

      Now add the highlighted line to store the user's input:

      greeting.go

      package main
      
      import (
          "fmt"
      )
      
      func main() {
        fmt.Println("Please enter your name.")
        var name string
      }
      

      The var name string line will create a new variable using the var keyword. You name the variable name, and it will be of type string.

      Then, add the highlighted line to capture the user's input:

      greeting.go

      package main
      
      import (
          "fmt"
      )
      
      func main() {
        fmt.Println("Please enter your name.")
        var name string
        fmt.Scanln(&name)
      }
      

      The fmt.Scanln method tells the computer to wait for input from the keyboard ending with a new line or (n), character. This pauses the program, allowing the user to enter any text they want. The program will continue when the user presses the ENTER key on their keyboard. All of the keystrokes, including the ENTER keystroke, are then captured and converted to a string of characters.

      You want to use those characters in your program's output, so you save those characters by writing them into the string variable called name. Go stores that string in your computer's memory until the program finishes running.

      Finally, add the following highlighted line in your program to print the output:

      greeting.go

      package main
      
      import (
          "fmt"
      )
      
      func main() {
        fmt.Println("Please enter your name.")
        var name string
        fmt.Scanln(&name)
        fmt.Printf("Hi, %s! I'm Go!", name)
      }
      

      This time, instead of using the fmt.Println method again, you're using fmt.Printf. The fmt.Printf function takes a string, and using special printing verbs, (%s), it injects the value of name into the string. You do this because Go does not support string interpolation, which would let you take the value assigned to a variable and place it inside of a string.

      Save and exit nano by pressing CTRL + X, and press Y when prompted to save the file.

      Now run the program. You'll be prompted for your name, so enter it and press ENTER. The output might not be exactly what you expect:

      Output

      Please enter your name. Sammy Hi, Sammy ! I'm Go!

      Instead of Hi, Sammy! I'm Go!, there's a line break right after the name.

      The program captured all of our keystrokes, including the ENTER key that we pressed to tell the program to continue. In a string, pressing the ENTER key creates a special character that creates a new line. The program's output is doing exactly what you told it to do; it's displaying the text you entered, including that new line. It's not what you expected the output to be, but you can fix it with additional functions.

      Open the greeting.go file in your editor:

      Locate this line in your program:

      greeting.go

      ...
      fmt.Scanln(&name)
      ...
      

      Add the following line right after it:

      greeting.go

      name = strings.TrimSpace(name)
      

      This uses the TrimSpace function, from Go's standard library strings package, on the string that you captured with fmt.Scanln. The strings.TrimSpace function removes any space characters, including new lines, from the start and end of a string. In this case, it removes the newline character at the end of the string created when you pressed ENTER.

      To use the strings package you need to import it at the top of the program.

      Locate these lines in your program:

      greeting.go

      import (
          "fmt"
      )
      

      Add the following line to import the strings package:

      greeting.go

      import (
          "fmt"
        "strings"
      )
      

      Your program will now contain the following:

      greeting.go

      package main
      
      import (
              "fmt"
              "strings"
      )
      
      func main() {
          fmt.Println("Please enter your name.")
          var name string
          fmt.Scanln(&name)
          fmt.Printf("Hi, %s! I'm Go!", name)
          name = strings.TrimSpace(name)
      }
      

      Save and exit nano. Press CTRL + X, then press Y when prompted to save the file.

      Run the program again:

      This time, after you enter your name and press ENTER, you get the expected output:

      Output

      Please enter your name. Sammy Hi, Sammy! I'm Go!

      You now have a Go program that takes input from a user and prints it back to the screen.

      Conclusion

      In this tutorial, you wrote a "Hello, World!" program that takes input from a user, processes the results, and displays the output. Now that you have a basic program to work with, try to expand your program further. For example, ask for the user's favorite color, and have the program say that its favorite color is red. You might even try to use this same technique to create a simple Mad-Lib program.



      Source link

      How To Write Comments in Go


      Introduction

      Comments are lines that exist in computer programs that are ignored by compilers and interpreters. Including comments in programs makes code more readable for humans as it provides some information or explanation about what each part of a program is doing.

      Depending on the purpose of your program, comments can serve as notes to yourself or reminders, or they can be written with the intention of other programmers being able to understand what your code is doing.

      In general, it is a good idea to write comments while you are writing or updating a program as it is easy to forget your thought process later on, and comments written later may be less useful in the long term.

      Comments in Go begin with a set of forward slashes (//) and continue to the end of the line. It is idiomatic to have a white space after the set of forward slashes.

      Generally, comments will look something like this:

      // This is a comment
      

      Comments do not execute, so there will be no indication of a comment when running a program. Comments are in the source code for humans to read, not for computers to execute.

      In a “Hello, World!” program, a comment may look like this:

      hello.go

      package main
      
      import (
          "fmt"
      )
      
      func main() {
          // Print “Hello, World!” to console
          fmt.Println("Hello, World!")
      }
      
      

      In a for loop that iterates over a slice, comments may look like this:

      sharks.go

      package main
      
      import (
          "fmt"
      )
      
      func main() {
          // Define sharks variable as a slice of strings
          sharks := []string{"hammerhead", "great white", "dogfish", "frilled", "bullhead", "requiem"}
      
          // For loop that iterates over sharks list and prints each string item
          for _, shark := range sharks {
              fmt.Println(shark)
          }
      }
      

      Comments should be made at the same indent as the code it is commenting. That is, a function definition with no indent would have a comment with no indent, and each indent level following would have comments that are aligned with the code it is commenting.

      For example, here is how the main function is commented, with comments following each indent level of the code:

      color.go

      package main
      
      import "fmt"
      
      const favColor string = "blue"
      
      func main() {
          var guess string
          // Create an input loop
          for {
              // Ask the user to guess my favorite color
              fmt.Println("Guess my favorite color:")
              // Try to read a line of input from the user. Print out the error 0
              if _, err := fmt.Scanln(&guess); err != nil {
                  fmt.Printf("%sn", err)
                  return
              }
              // Did they guess the correct color?
              if favColor == guess {
                  // They guessed it!
                  fmt.Printf("%q is my favorite color!n", favColor)
                  return
              }
              // Wrong! Have them guess again.
              fmt.Printf("Sorry, %q is not my favorite color. Guess again.n", guess)
          }
      }
      

      Comments are made to help programmers, whether it is the original programmer or someone else using or collaborating on the project. If comments cannot be properly maintained and updated along with the code base, it is better to not include a comment rather than write a comment that contradicts or will contradict the code.

      When commenting code, you should be looking to answer the why behind the code as opposed to the what or how. Unless the code is particularly tricky, looking at the code can generally answer the what or how, which is why comments are usually focused around the why.

      Block comments can be used to explain more complicated code or code that you don’t expect the reader to be familiar with.

      You can create block comments two ways in Go. The first is by using a set of double forward slashes and repeating them for every line.

      // First line of a block comment
      // Second line of a block comment
      

      The second is to use opening tags (/*) and closing tags (*/). For documenting code, it is considered idiomatic to always use // syntax. You would only use the /* ... */ syntax for debugging, which we will cover later in this article.

      /*
      Everything here
      will be considered
      a block comment
      */
      

      In this example, the block comment defines what is happening in the MustGet() function:

      function.go

      // MustGet will retrieve a url and return the body of the page.
      // If Get encounters any errors, it will panic.
      func MustGet(url string) string {
          resp, err := http.Get(url)
          if err != nil {
              panic(err)
          }
      
          // don't forget to close the body
          defer resp.Body.Close()
          var body []byte
          if body, err = ioutil.ReadAll(resp.Body); err != nil {
              panic(err)
          }
          return string(body)
      }
      

      It is common to see block comments at the beginning of exported functions in Go; these comments are also what generate your code documentation. Block comments are also used when operations are less straightforward and are therefore demanding of a thorough explanation. With the exception of documenting functions, you should try to avoid over-commenting the code and trust other programmers to understand Go, unless you are writing for a particular audience.

      Inline comments occur on the same line of a statement, following the code itself. Like other comments, they begin with a set of forward slashes. Again, it’s not required to have a whitespace after the forward slashes, but it is considered idiomatic to do so.

      Generally, inline comments look like this:

      [code]  // Inline comment about the code
      

      Inline comments should be used sparingly, but can be effective for explaining tricky or non-obvious parts of code. They can also be useful if you think you may not remember a line of the code you are writing in the future, or if you are collaborating with someone who you know may not be familiar with all aspects of the code.

      For example, if you don’t use a lot of math in your Go programs, you or your collaborators may not know that the following creates a complex number, so you may want to include an inline comment about that:

      z := x % 2  // Get the modulus of x
      

      You can also use inline comments to explain the reason behind doing something, or to provide some extra information, as in:

      x := 8  // Initialize x with an arbitrary number
      

      You should only use inline comments when necessary and when they can provide helpful guidance for the person reading the program.

      In addition to using comments as a way to document code, you can also use opening tags (/*) and closing tags (*/) to create a block comment. This allows you to comment out code that you don’t want to execute while you are testing or debugging a program you are currently creating. That is, when you experience errors after implementing new lines of code, you may want to comment a few of them out to see if you can troubleshoot the precise issue.

      Using the /* and */ tags can also allow you to try alternatives while you’re determining how to set up your code. You can also use block comments to comment out code that is failing while you continue to work on other parts of your code.

      multiply.go

      // Function to add two numbers
      func addTwoNumbers(x, y int) int {
          sum := x + y
          return sum
      }
      
      // Function to multiply two numbers
      func multiplyTwoNumbers(x, y int) int {
          product := x * y
          return product
      }
      
      func main() {
          /*
              In this example, we're commenting out the addTwoNumbers
              function because it is failing, therefore preventing it from executing.
              Only the multiplyTwoNumbers function will run
      
              a := addTwoNumbers(3, 5)
              fmt.Println(a)
      
          */
      
          m := multiplyTwoNumbers(5, 9)
          fmt.Println(m)
      }
      

      Note: Commenting out code should only be done for testing purposes. Do not leave snippets of commented out code in your final program.

      Commenting out code with the /* and */ tags can allow you to try out different programming methods as well as help you find the source of an error through systematically commenting out and running parts of a program.

      Conclusion

      Using comments within your Go programs helps to make your programs more readable for humans, including your future self. Adding appropriate comments that are relevant and useful can make it easier for others to collaborate with you on programming projects and make the value of your code more obvious.

      Commenting your code properly in Go will also allow for you to use the Godoc tool. Godoc is a tool that will extract comments from your code and generate documentation for your Go program.



      Source link