One place for hosting & domains

      How To Write Conditional Statements in Go


      Introduction

      Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

      When we fully execute each statement of a program, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.

      Let’s look at some examples where we would use conditional statements:

      • If the student receives over 65% on her test, report that her grade passes; if not, report that her grade fails.
      • If he has money in his account, calculate interest; if he doesn’t, charge a penalty fee.
      • If they buy 10 oranges or more, calculate a discount of 5%; if they buy fewer, then don’t.

      Through evaluating conditions and assigning code to run based on whether or not those conditions are met, we are writing conditional code.

      This tutorial will take you through writing conditional statements in the Go programming language.

      If Statements

      We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

      In a plain text editor, open a file and write the following code:

      grade.go

      package main
      
      import "fmt"
      
      func main() {
          grade := 70
      
          if grade >= 65 {
              fmt.Println("Passing grade")
          }
      }
      

      With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65. If it does meet this condition, we are telling the program to print out the string Passing grade.

      Save the program as grade.go and run it in a local programming environment from a terminal window with the command go run grade.go.

      In this case, the grade of 70 does meet the condition of being greater than or equal to 65, so you will receive the following output once you run the program:

      Output

      Passing grade

      Let’s now change the result of this program by changing the value of the grade variable to 60:

      grade.go

      package main
      
      import "fmt"
      
      func main() {
          grade := 60
      
          if grade >= 65 {
              fmt.Println("Passing grade")
          }
      }
      

      When we save and run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.

      To give one more example, let us calculate whether a bank account balance is below 0. Let’s create a file called account.go and write the following program:

      account.go

      package main
      
      import "fmt"
      
      func main() {
          balance := -5
      
          if balance < 0 {
              fmt.Println("Balance is below 0, add funds now or you will be charged a penalty.")
          }
      }
      

      When we run the program with go run account.go, we’ll receive the following output:

      Output

      Balance is below 0, add funds now or you will be charged a penalty.

      In the program we initialized the variable balance with the value of -5, which is less than 0. Since the balance met the condition of the if statement (balance < 0), once we save and run the code, we will receive the string output. Again, if we change the balance to 0 or a positive number, we will receive no output.

      Else Statements

      It is likely that we will want the program to do something even when an if statement evaluates to false. In our grade example, we will want output whether the grade is passing or failing.

      To do this, we will add an else statement to the grade condition above that is constructed like this:

      grade.go

      package main
      
      import "fmt"
      
      func main() {
          grade := 60
      
          if grade >= 65 {
              fmt.Println("Passing grade")
          } else {
              fmt.Println("Failing grade")
          }
      }
      

      Since the grade variable has the value of 60, the if statement evaluates as false, so the program will not print out Passing grade. The else statement that follows tells the program to do something anyway.

      When we save and run the program, we’ll receive the following output:

      Output

      Failing grade

      If we then rewrite the program to give the grade a value of 65 or higher, we will instead receive the output Passing grade.

      To add an else statement to the bank account example, we rewrite the code like this:

      account.go

      package main
      
      import "fmt"
      
      func main() {
          balance := 522
      
          if balance < 0 {
              fmt.Println("Balance is below 0, add funds now or you will be charged a penalty.")
          } else {
              fmt.Println("Your balance is 0 or above.")
          }
      }
      

      Output

      Your balance is 0 or above.

      Here, we changed the balance variable value to a positive number so that the else statement will print. To get the first if statement to print, we can rewrite the value to a negative number.

      By combining an if statement with an else statement, you are constructing a two-part conditional statement that will tell the computer to execute certain code whether or not the if condition is met.

      Else if Statements

      So far, we have presented a Boolean option for conditional statements, with each if statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Go as else if. The else if or else if statement looks like the if statement and will evaluate another condition.

      In the bank account program, we may want to have three discrete outputs for three different situations:

      • The balance is below 0
      • The balance is equal to 0
      • The balance is above 0

      The else if statement will be placed between the if statement and the else statement as follows:

      account.go

      package main
      
      import "fmt"
      
      func main() {
          balance := 522
      
          if balance < 0 {
              fmt.Println("Balance is below 0, add funds now or you will be charged a penalty.")
          } else if balance == 0 {
              fmt.Println("Balance is equal to 0, add funds soon.")
          } else {
              fmt.Println("Your balance is 0 or above.")
          }
      }
      

      Now, there are three possible outputs that can occur once we run the program:

      • If the variable balance is equal to 0 we will receive the output from the else if statement (Balance is equal to 0, add funds soon.)
      • If the variable balance is set to a positive number, we will receive the output from the else statement (Your balance is 0 or above.).
      • If the variable balance is set to a negative number, the output will be the string from the if statement (Balance is below 0, add funds now or you will be charged a penalty).

      What if we want to have more than three possibilities, though? We can do this by writing more than one else if statement into our code.

      In the grade.go program, let’s rewrite the code so that there are a few letter grades corresponding to ranges of numerical grades:

      • 90 or above is equivalent to an A grade
      • 80-89 is equivalent to a B grade
      • 70-79 is equivalent to a C grade
      • 65-69 is equivalent to a D grade
      • 64 or below is equivalent to an F grade

      To run this code, we will need one if statement, three else if statements, and an else statement that will handle all failing cases.

      Let’s rewrite the code from the preceding example to have strings that print out each of the letter grades. We can keep our else statement the same.

      grade.go

      package main
      
      import "fmt"
      
      func main() {
          grade := 60
      
          if grade >= 90 {
              fmt.Println("A grade")
          } else if grade >= 80 {
              fmt.Println("B grade")
          } else if grade >= 70 {
              fmt.Println("C grade")
          } else if grade >= 65 {
              fmt.Println("D grade")
          } else {
              fmt.Println("Failing grade")
          }
      }
      

      Since else if statements will evaluate in order, we can keep our statements pretty basic. This program is completing the following steps:

      1. If the grade is greater than 90, the program will print A grade, if the grade is less than 90, the program will continue to the next statement…

      2. If the grade is greater than or equal to 80, the program will print B grade, if the grade is 79 or less, the program will continue to the next statement…

      3. If the grade is greater than or equal to 70, the program will print C grade, if the grade is 69 or less, the program will continue to the next statement…

      4. If the grade is greater than or equal to 65, the program will print D grade, if the grade is 64 or less, the program will continue to the next statement…

      5. The program will print Failing grade because all of the above conditions were not met.

      Nested If Statements

      Once you are feeling comfortable with the if, else if, and else statements, you can move on to nested conditional statements. We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:

      if statement1 { // outer if statement
          fmt.Println("true")
      
          if nested_statement { // nested if statement
              fmt.Println("yes")
          } else { // nested else statement
              fmt.Println("no")
          }
      
      } else { // outer else statement
          fmt.Println("false")
      }
      

      A few possible outputs can result from this code:

      • If statement1 evaluates to true, the program will then evaluate whether the nested_statement also evaluates to true. If both cases are true, the output will be:

      Output

      true yes
      • If, however, statement1 evaluates to true, but nested_statement evaluates to false, then the output will be:

      Output

      true no
      • And if statement1 evaluates to false, the nested if-else statement will not run, so the else statement will run alone, and the output will be:

      Output

      false

      We can also have multiple if statements nested throughout our code:

      if statement1 { // outer if
          fmt.Println("hello world")
      
          if nested_statement1 { // first nested if
              fmt.Println("yes")
      
          } else if nested_statement2 { // first nested else if
              fmt.Println("maybe")
      
          } else { // first nested else
              fmt.Println("no")
          }
      
      } else if statement2 { // outer else if
          fmt.Println("hello galaxy")
      
          if nested_statement3 { // second nested if
              fmt.Println("yes")
          } else if nested_statement4 { // second nested else if
              fmt.Println("maybe")
          } else { // second nested else
              fmt.Println("no")
          }
      
      } else { // outer else
          statement("hello universe")
      }
      

      In this code, there is a nested if statement inside each if statement in addition to the else if statement. This will allow for more options within each condition.

      Let’s look at an example of nested if statements with our grade.go program. We can check for whether a grade is passing first (greater than or equal to 65%), then evaluate which letter grade the numerical grade should be equivalent to. If the grade is not passing, though, we do not need to run through the letter grades, and instead can have the program report that the grade is failing. Our modified code with the nested if statement will look like this:

      grade.go

      
      package main
      
      import "fmt"
      
      func main() {
          grade := 92
          if grade >= 65 {
              fmt.Print("Passing grade of: ")
      
              if grade >= 90 {
                  fmt.Println("A")
      
              } else if grade >= 80 {
                  fmt.Println("B")
      
              } else if grade >= 70 {
                  fmt.Println("C")
      
              } else if grade >= 65 {
                  fmt.Println("D")
              }
      
          } else {
              fmt.Println("Failing grade")
          }
      }
      

      If we run the code with the variable grade set to the integer value 92, the first condition is met, and the program will print out Passing grade of:. Next, it will check to see if the grade is greater than or equal to 90, and since this condition is also met, it will print out A.

      If we run the code with the grade variable set to 60, then the first condition is not met, so the program will skip the nested if statements and move down to the else statement, with the program printing out Failing grade.

      We can of course add even more options to this, and use a second layer of nested if statements. Perhaps we will want to evaluate for grades of A+, A and A- separately. We can do so by first checking if the grade is passing, then checking to see if the grade is 90 or above, then checking to see if the grade is over 96 for an A+:

      grade.go

      …
      if grade >= 65 {
          fmt.Print("Passing grade of: ")
      
          if grade >= 90 {
              if grade > 96 {
                  fmt.Println("A+")
      
              } else if grade > 93 && grade <= 96 {
                  fmt.Println("A")
      
              } else {
                  fmt.Println("A-")
              }
      …
      

      In this code, for a grade variable set to 96, the program will run the following:

      1. Check if the grade is greater than or equal to 65 (true)
      2. Print out Passing grade of:
      3. Check if the grade is greater than or equal to 90 (true)
      4. Check if the grade is greater than 96 (false)
      5. Check if the grade is greater than 93 and also less than or equal to 96 (true)
      6. Print A
      7. Leave these nested conditional statements and continue with remaining code

      The output of the program for a grade of 96 therefore looks like this:

      Output

      Passing grade of: A

      Nested if statements can provide the opportunity to add several specific levels of conditions to your code.

      Conclusion

      By using conditional statements like the if statement, you will have greater control over what your program executes. Conditional statements tell the program to evaluate whether a certain condition is being met. If the condition is met it will execute specific code, but if it is not met the program will continue to move down to other code.

      To continue practicing conditional statements, try using different operators to gain more familiarity with conditional statements.



      Source link

      How To Write and Run Your First Program in Node.js


      The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Node.js is a popular open-source runtime environment that can execute JavaScript outside of the browser using the V8 JavaScript engine, which is the same engine used to power the Google Chrome web browser’s JavaScript execution. The Node runtime is commonly used to create command line tools and web servers.

      Learning Node.js will allow you to write your front-end code and your back-end code in the same language. Using JavaScript throughout your entire stack can help reduce time for context switching, and libraries are more easily shared between your back-end server and front-end projects.

      Also, thanks to its support for asynchronous execution, Node.js excels at I/O-intensive tasks, which is what makes it so suitable for the web. Real-time applications, like video streaming, or applications that continuously send and receive data, can run more efficiently when written in Node.js.

      In this tutorial you’ll create your first program with the Node.js runtime. You’ll be introduced to a few Node-specific concepts and build your way up to create a program that helps users inspect environment variables on their system. To do this, you’ll learn how to output strings to the console, receive input from the user, and access environment variables.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Outputting to the Console

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

      With the text editor opened, enter the following code:

      hello.js

      console.log("Hello World");
      

      The console object in Node.js provides simple methods to write to stdout, stderr, or to any other Node.js stream, which in most cases is the command line. The log method prints to the stdout stream, so you can see it in your console.

      In the context of Node.js, streams are objects that can either receive data, like the stdout stream, or objects that can output data, like a network socket or a file. In the case of the stdout and stderr streams, any data sent to them will then be shown in the console. One of the great things about streams is that they're easily redirected, in which case you can redirect the output of your program to a file, for example.

      Save and exit nano by pressing CTRL+X, when prompted to save the file, press Y. Now your program is ready to run.

      Step 2 — Running the Program

      To run this program, use the node command as follows:

      The hello.js program will execute and display the following output:

      Output

      Hello World

      The Node.js interpreter read the file and executed console.log("Hello World"); by calling the log method of the global console object. The string "Hello World" was passed as an argument to the log function.

      Although quotation marks are necessary in the code to indicate that the text is a string, they are not printed to the screen.

      Having confirmed that the program works, let's make it more interactive.

      Step 3 — Receiving User Input via Command Line Arguments

      Every time you run the Node.js “Hello, World!” program, it produces the same output. In order to make the program more dynamic, let's get input from the user and display it on the screen.

      Command line tools often accept various arguments that modify their behavior. For example, running node with the --version argument prints the installed version instead of running the interpreter. In this step, you will make your code accept user input via command line arguments.

      Create a new file arguments.js with nano:

      Enter the following code:

      arguments.js

      console.log(process.argv);
      

      The process object is a global Node.js object that contains functions and data all related to the currently running Node.js process. The argv property is an array of strings containing all the command line arguments given to a program.

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

      Now when you run this program, you provide a command line argument like this:

      • node arguments.js hello world

      The output looks like the following:

      Output

      [ '/usr/bin/node', '/home/sammy/first-program/arguments.js', 'hello', 'world' ]

      The first argument in the process.argv array is always the location of the Node.js binary that is running the program. The second argument is always the location of the file being run. The remaining arguments are what the user entered, in this case: hello and world.

      We are mostly interested in the arguments that the user entered, not the default ones that Node.js provides. Open the arguments.js file for editing:

      Change console.log(process.arg); to the following:

      arguments.js

      console.log(process.argv.slice(2));
      

      Because argv is an array, you can use JavaScript's built-in slice method that returns a selection of elements. When you provide the slice function with 2 as its argument, you get all the elements of argv that comes after its second element; that is, the arguments the user entered.

      Re-run the program with the node command and the same arguments as last time:

      • node arguments.js hello world

      Now, the output looks like this:

      Output

      [ 'hello', 'world' ]

      Now that you can collect input from the user, let's collect input from the program's environment.

      Step 4 — Accessing Environment Variables

      Environment variables are key-value data stored outside of a program and provided by the OS. They are typically set by the system or user and are available to all running processes for configuration or state purposes. You can use Node's process object to access them.

      Use nano to create a new file environment.js:

      Add the following code:

      environment.js

      console.log(process.env);
      

      The env object stores all the environment variables that are available when Node.js is running the program.

      Save and exit like before, and run the environment.js file with the node command.

      Upon running the program, you should see output similar to the following:

      Output

      { SHELL: '/bin/bash', SESSION_MANAGER: 'local/digitalocean:@/tmp/.ICE-unix/1003,unix/digitalocean:/tmp/.ICE-unix/1003', COLORTERM: 'truecolor', SSH_AUTH_SOCK: '/run/user/1000/keyring/ssh', XMODIFIERS: '@im=ibus', DESKTOP_SESSION: 'ubuntu', SSH_AGENT_PID: '1150', PWD: '/home/sammy/first-program', LOGNAME: 'sammy', GPG_AGENT_INFO: '/run/user/1000/gnupg/S.gpg-agent:0:1', GJS_DEBUG_TOPICS: 'JS ERROR;JS LOG', WINDOWPATH: '2', HOME: '/home/sammy', USERNAME: 'sammy', IM_CONFIG_PHASE: '2', LANG: 'en_US.UTF-8', VTE_VERSION: '5601', CLUTTER_IM_MODULE: 'xim', GJS_DEBUG_OUTPUT: 'stderr', LESSCLOSE: '/usr/bin/lesspipe %s %s', TERM: 'xterm-256color', LESSOPEN: '| /usr/bin/lesspipe %s', USER: 'sammy', DISPLAY: ':0', SHLVL: '1', PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus', _: '/usr/bin/node', OLDPWD: '/home/sammy' }

      Keep in mind that many of the environment variables you see are dependent on the configuration and settings of your system, and your output may look substantially different than what you see here. Rather than viewing a long list of environment variables, you might want to retrieve a specific one.

      Step 5 — Accessing a Specified Environment Variable

      In this step you'll view environment variables and their values using the global process.env object and print their values to the console.

      The process.env object is a simple mapping between environment variable names and their values stored as strings. Like all objects in JavaScript, you access an individual property by referencing its name in square brackets.

      Open the environment.js file for editing:

      Change console.log(process.env); to:

      environment.js

      console.log(process.env["HOME"]);
      

      Save the file and exit. Now run the environment.js program:

      The output now looks like this:

      Output

      /home/sammy

      Instead of printing the entire object, you now only print the HOME property of process.env, which stores the value of the $HOME environment variable.

      Again, keep in mind that the output from this code will likely be different than what you see here because it is specific to your system. Now that you can specify the environment variable to retrieve, you can enhance your program by asking the user for the variable they want to see.

      Step 6 — Retrieving An Argument in Response to User Input

      Next, you'll use the ability to read command line arguments and environment variables to create a command line utility that prints the value of an environment variable to the screen.

      Use nano to create a new file echo.js:

      Add the following code:

      echo.js

      const args = process.argv.slice(2);
      console.log(process.env[args[0]]);
      

      The first line of echo.js stores all the command line arguments that the user provided into a constant variable called args. The second line prints the environment variable stored in the first element of args; that is, the first command line argument the user provided.

      Save and exit nano, then run the program as follows:

      Now, the output would be:

      Output

      /home/sammy

      The argument HOME was saved to the args array, which was then used to find its value in the environment via the process.env object.

      At this point you can now access the value of any environment variable on your system. To verify this, try viewing the following variables: PWD, USER, PATH.

      Retrieving single variables is good, but letting the user specify how many variables they want would be better.

      Step 7 — Viewing Multiple Environment Variables

      Currently, the application can only inspect one environment variable at a time. It would be useful if we could accept multiple command line arguments and get their corresponding value in the environment. Use nano to edit echo.js:

      Edit the file so that it has the following code instead:

      echo.js

      const args = process.argv.slice(2);
      
      args.forEach(arg => {
        console.log(process.env[arg]);
      });
      

      The forEach method is a standard JavaScript method on all array objects. It accepts a callback function that is used as it iterates over every element of the array. You use forEach on the args array, providing it a callback function that prints the current argument's value in the environment.

      Save and exit the file. Now re-run the program with two arguments:

      You would see the following output:

      Output

      /home/sammy /home/sammy/first-program

      The forEach function ensures that every command line argument in the args array is printed.

      Now you have a way to retrieve the variables the user asks for, but we still need to handle the case where the user enters bad data.

      Step 8 — Handling Undefined Input

      To see what happens if you give the program an argument that is not a valid environment variable, run the following:

      • node echo.js HOME PWD NOT_DEFINED

      The output will look similar to the following:

      Output

      /home/sammy /home/sammy/first-program undefined

      The first two lines print as expected, and the last line only has undefined. In JavaScript, an undefined value means that a variable or property has not been assigned a value. Because NOT_DEFINED is not a valid environment variable, it is shown as undefined.

      It would be more helpful to a user to see an error message if their command line argument was not found in the environment.

      Open echo.js for editing:

      Edit echo.js so that it has the following code:

      echo.js

      const args = process.argv.slice(2);
      
      args.forEach(arg => {
        let envVar = process.env[arg];
        if (envVar === undefined) {
          console.error(`Could not find "${arg}" in environment`);
        } else {
          console.log(envVar);
        }
      });
      

      Here, you have modified the callback function provided to forEach to do the following things:

      1. Get the command line argument's value in the environment and store it in a variable envVar.
      2. Check if the value of envVar is undefined.
      3. If the envVar is undefined, then we print a helpful message indicating that it could not be found.
      4. If an environment variable was found, we print its value.

      Note: The console.error function prints a message to the screen via the stderr stream, whereas console.log prints to the screen via the stdout stream. When you run this program via the command line, you won't notice the difference between the stdout and stderr streams, but it is good practice to print errors via the stderr stream so that they can be easier identified and processed by other programs, which can tell the difference.

      Now run the following command once more:

      • node echo.js HOME PWD NOT_DEFINED

      This time the output will be:

      Output

      /home/sammy /home/sammy/first-program Could not find "NOT_DEFINED" in environment

      Now when you provide a command line argument that's not an environment variable, you get a clear error message stating so.

      Conclusion

      Your first program displayed "Hello World" to the screen, and now you have written a Node.js command line utility that reads user arguments to display environment variables.

      If you want to take this further, you can change the behavior of this program even more. For example, you may want to validate the command line arguments before you print. If an argument is undefined, you can return an error, and the user will only get output if all arguments are valid environment variables.



      Source link

      How To Write Packages in Go


      A package is made up of Go files that live in the same directory and have the same package statement at the beginning. You can include additional functionality from packages to make your programs more sophisticated. Some packages are available through the Go Standard Library and are therefore installed with your Go installation. Others can be installed with Go’s go get command. You can also build your own Go packages by creating Go files in the same directory across which you want to share code by using the necessary package statement.

      This tutorial will guide you through writing Go packages for use within other programming files.

      Prerequisites

      Writing and Importing Packages

      Writing a package is just like writing any other Go file. Packages can contain definitions of functions, types, and variables that can then be used in other Go programs.

      Before we create a new package, we need to be in our Go workspace. This is typically under our gopath. For the example, in this tutorial we will call the package greet. To do this, we’ve created a directory called greet in our gopath under our project space. If our organization were gopherguides, and we wanted to create the greet package under the organization while using Github as our code repository, then our directory would look like this:

      └── $GOPATH
          └── src
              └── github.com
                  └── gopherguides
      

      The greet directory is within the gopherguides directory:

      └── $GOPATH
          └── src
              └── github.com
                  └── gopherguides
                      └── greet
      

      Finally, we can add the first file in our directory. It is considered common practice that the primary or entry point file in a package is named after the name of the directory. In this case, we would create a file called greet.go inside the greet directory:

      └── $GOPATH
          └── src
              └── github.com
                  └── gopherguides
                      └── greet
                          └── greet.go
      

      With the file created, we can begin to write our code that we want to reuse or share across projects. In this case, we will create a function called Hello that prints out Hello World.

      Open your greet.go file in your text editor and add the following code:

      greet.go

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

      Let’s break this first file down. The first line of each file needs the name of the package that you are working in. Since you’re in the greet package, you use the package keyword followed by the name of the package:

      package greet
      

      This will tell the compiler to treat everything in the file as being part of the greet package.

      Next you declare any other packages you need to use with the import statement. You’re only using one in this file—the fmt package:

      import "fmt"
      

      Lastly, you create the function Hello. It will use the fmt package to print out Hello, World!:

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

      Now that you’ve written the greet package, you can use it in any other package you create. Let’s create a new package in which you’ll use your greet package.

      You’re going to create a package called example, which means you need a directory called example. Create this package in your gopherguides organization, so the directory structure looks like so:

      └── $GOPATH
          └── src
              └── github.com
                  └── gopherguides
                          └── example
      

      Now that you have your directory for your new package, you can create the entry point file. Because this is going to be an executable program, it is considered best practice to name the entry point file main.go:

      └── $GOPATH
          └── src
              └── github.com
                  └── gopherguides
                      └── example
                          └── main.go
      

      In your text editor, open main.go and add the following code to call the greet package:

      main.go

      package main
      
      import "github.com/gopherguides/greet"
      
      func main() {
          greet.Hello()
      }
      

      Because you’re importing a package, you need to call the function by referencing the package name in dot notation. Dot notation is the practice of putting a period . between the name of the package you are using and the resource within that package that you want to use. For instance, in your greet package, you have the Hello function as a resource. If you want to call that resource, you use the dot notation of greet.Hello().

      Now, you can open your terminal and run the program on the command line:

      When you do, you’ll receive the following output:

      Output

      Hello, World!

      To see how you can use variables in a package, let’s add a variable definition in your greet.go file:

      greet.go

      package greet
      
      import "fmt"
      
      var Shark = "Sammy"
      
      func Hello() {
          fmt.Println("Hello, World!")
      }
      

      Next, open your main.go file and add the following highlighted line to call the variable from greet.go in a fmt.Println() function:

      main.go

      package main
      
      import (
          "fmt"
      
          "github.com/gopherguides/greet"
      )
      
      func main() {
          greet.Hello()
      
          fmt.Println(greet.Shark)
      }
      

      Once you run the program again:

      You’ll receive the following output:

      Output

      Hello, World! Sammy

      Finally, let’s also define a type in the greet.go file. You’ll create the type Octopus with name and color fields, and a function that will print out the fields when called:

      greet.go

      package greet
      
      import "fmt"
      
      var Shark = "Sammy"
      
      type Octopus struct {
          Name  string
          Color string
      }
      
      func (o Octopus) String() string {
          return fmt.Sprintf("The octopus's name is %q and is the color %s.", o.Name, o.Color)
      }
      
      func Hello() {
          fmt.Println("Hello, World!")
      }
      

      Open main.go to create an instance of that type at the end of the file:

      main.go

      package main
      
      import (
          "fmt"
      
          "github.com/gopherguides/greet"
      )
      
      func main() {
          greet.Hello()
      
          fmt.Println(greet.Shark)
      
          oct := greet.Octopus{
              Name:  "Jesse",
              Color: "orange",
          }
      
          fmt.Println(oct.String())
      }
      

      Once you've created an instance of Octopus type with oct := greet.Octopus, you can access the functions and fields of the type within the main.go file’s namespace. This lets you write oct.String() on the last line without invoking greet. You could also, for example, call one of the types fields such as oct.Color without referencing the name of the greet package.

      The String method on the Octopus type uses the fmt.Sprintf function to create a sentence, and returns the result, a string, to the caller (in this case, your main program).

      When you run the program, you’ll receive the following output:

      Output

      Hello, World! Sammy The octopus's name is "Jesse" and is the color orange.

      By creating the String method on Octopus, you now have a reusable way to print out information about your custom type. If you want to change the behavior of this method in the future, you only have to edit this one method.

      Exported Code

      You may have noticed that all of the declarations in the greet.go file you called were capitalized. Go does not have the concept of public, private, or protected modifiers like other languages do. External visibility is controlled by capitalization. Types, variables, functions, and so on, that start with a capital letter are available, publicly, outside the current package. A symbol that is visible outside its package is considered to be exported.

      If you add a new method to Octopus called reset, you can call it from within the greet package, but not from your main.go file, which is outside the greet package:

      greet.go

      package greet
      
      import "fmt"
      
      var Shark = "Sammy"
      
      type Octopus struct {
          Name  string
          Color string
      }
      
      func (o Octopus) String() string {
          return fmt.Sprintf("The octopus's name is %q and is the color %s.", o.Name, o.Color)
      }
      
      func (o Octopus) reset() {
          o.Name = ""
          o.Color = ""
      }
      
      func Hello() {
          fmt.Println("Hello, World!")
      }
      
      

      If you try to call reset from the main.go file:

      main.go

      package main
      
      import (
          "fmt"
      
          "github.com/gopherguides/greet"
      )
      
      func main() {
          greet.Hello()
      
          fmt.Println(greet.Shark)
      
          oct := greet.Octopus{
              Name:  "Jesse",
              Color: "orange",
          }
      
          fmt.Println(oct.String())
      
          oct.reset()
      }
      

      You'll receive the following compilation error:

      Output

      oct.reset undefined (cannot refer to unexported field or method greet.Octopus.reset)

      To export the reset functionality from Octopus, capitalize the R in reset:

      greet.go

      package greet
      
      import "fmt"
      
      var Shark = "Sammy"
      
      type Octopus struct {
          Name  string
          Color string
      }
      
      func (o Octopus) String() string {
          return fmt.Sprintf("The octopus's name is %q and is the color %s.", o.Name, o.Color)
      }
      
      func (o Octopus) Reset() {
          o.Name = ""
          o.Color = ""
      }
      
      func Hello() {
          fmt.Println("Hello, World!")
      }
      

      As a result you can call Reset from your other package without getting an error:

      main.go

      package main
      
      import (
          "fmt"
      
          "github.com/gopherguides/greet"
      )
      
      func main() {
          greet.Hello()
      
          fmt.Println(greet.Shark)
      
          oct := greet.Octopus{
              Name:  "Jesse",
              Color: "orange",
          }
      
          fmt.Println(oct.String())
      
          oct.Reset()
      
          fmt.Println(oct.String())
      }
      

      Now if you run the program:

      You will receive the following output:

      Output

      Hello, World! Sammy The octopus's name is "Jesse" and is the color orange The octopus's name is "" and is the color .

      By calling Reset, you cleared out all the information in the Name and Color fields. When you call the String method, it will print nothing where Name and Color normally appear because the fields are now empty.

      Conclusion

      Writing a Go package is the same as writing any other Go file, but placing it in another directory allows you to isolate the code to be reused elsewhere. This tutorial covered how to write definitions within a package, demonstrated how to make use of those definitions within another Go programming file, and explained the options for where to keep the package in order to access it.



      Source link