One place for hosting & domains

      packages

      Importing Packages in Go


      Introduction

      There will be times when your code needs additional functionality outside of your current program. In these cases, you can use packages to make your program more sophisticated. A package represents all the files in a single directory on disk. Packages can define functions, types, and interfaces that you can reference in other Go files or packages.

      This tutorial will walk you through installing, importing, and aliasing packages.

      Standard Library Packages

      The standard library that ships with Go is a set of packages. These packages contain many of the fundamental building blocks to write modern software. For instance, the fmt package contains basic functions for formatting and printing strings. The net/http package contains functions that allow a developer to create web services, send and retrieve data over the http protocol, and more.

      To make use of the functions in a package, you need to access the package with an import statement. An import statement is made up of the import keyword along with the name of the package.

      As an example, in the Go program file random.go you can import the math/rand package to generate random numbers in this manner:

      random.go

      import "math/rand"
      

      When we import a package, we are making it available in our current program as a separate namespace. This means that we will have to refer to the function in dot notation, as in package.function.

      In practice, a function from the math/rand package could look like these examples:

      • rand.Int() which calls the function to return a random integer.
      • rand.Intn() which calls the function to return a random element from 0 up to the specified number provided.

      Let’s create a for loop to show how we will call a function of the math/rand package within our random.go program:

      random.go

      package main
      
      import "math/rand"
      
      func main() {
        for i := 0; i < 10; i++ {
          println(rand.Intn(25))
        }
      }
      

      This program first imports the math/rand package on the third line, then moves into a for loop which that will run 10 times. Within the loop, the program will print a random integer within the range of 0 up to 25. The integer 25 is passed to rand.Intn() as its parameter.

      When we run the program with go run random.go, we’ll receive 10 random integers as output. Because these are random, you’ll likely get different integers each time you run the program. The output will look something like this:

      Output

      6 12 22 9 6 18 0 15 6 0

      The integers will never go below 0 or above 24.

      When importing more than one package, you can use the () to create a block. By using a block you can avoid repeating the import keyword on every line. This will make your code look cleaner:

      random.go

      
      import (
        "fmt"
        "math/rand"
      )
      

      To make use of the additional package, we can now format the output and print out the iteration that each random number was generated on during the loop:

      random.go

      package main
      
      import (
        "fmt"
        "math/rand"
      )
      
      func main() {
        for i := 0; i < 10; i++ {
          fmt.Printf("%d) %dn", i, rand.Intn(25))
        }
      }
      

      Now, when we run our program, we’ll receive output that looks like this:

      Output

      0) 6 1) 12 2) 22 3) 9 4) 6 5) 18 6) 0 7) 15 8) 6 9) 0

      In this section, we learned how to import packages and use them to write a more sophisticated program. So far, we have only used packages from the standard library. Next, let’s see how to install and use packages that are written by other developers.

      Installing Packages

      While the standard library ships with many great and useful packages, they are intentionally designed to be general purpose and not specific in nature. This allows developers to build their own packages on top of the standard library for their own specific needs.

      The Go tool chain ships with the go get command. This command allows you to install third party packages to your local development environment and use them in your program.

      When using go get to install third party packages, it is common for a package to be referenced by its canonical path. That path can also be a path to a public project that is hosted in a code repository such as GitHub. As such, if you want to import the flect package, you would use the full canonical path:

      • go get github.com/gobuffalo/flect

      The go get tool will find the package, on GitHub in this case, and install it into your $GOPATH.

      For this example the code would be installed in this directory:

      $GOPATH/src/github.com/gobuffalo/flect
      

      Packages are often being updated by the original authors to address bugs or add new features. When this happens, you may want to use the latest version of that package to take advantage of the new features or resolved bug. To update a package, you can use the -u flag with the go get command:

      • go get -u github.com/gobuffalo/flect

      This command will also have Go install the package if it is not found locally. If it is already installed, Go will attempt to update the package to the latest version.

      The go get command always retrieves the latest version of the package available. However, there may be updates to previous versions of the package that are still newer than you are using, and would be useful to update in your program. To retrieve that specific version of the package, you would need to use a Package Management tool, such as Go Modules.

      As of Go 1.11, Go Modules are used to manage what version of the package you want imported. The topic of package management is beyond the scope of this article, but you can read more about it on the Go Modules GitHub page.

      Aliasing Imported Packages

      You may want to change a package name if you have a local package already named the same as a third party package you are using. When this happens, aliasing your import is the best way to handle the collision. You can modify the names of packages and their functions within Go by putting an alias name in front of the imported package.

      The construction of this statement looks like this:

      import another_name "package"
      

      In this example, modify the name of the fmt package in the random.go program file. We’ll change the package name of fmt to f in order to abbreviate it. Our modified program will look like this:

      random.go

      package main
      
      import (
       f "fmt"
        "math/rand"
      )
      
      func main() {
        for i := 0; i < 10; i++ {
          f.Printf("%d) %dn", i, rand.Intn(25))
        }
      }
      

      Within the program, we now refer to the Printf function as f.Printf rather than fmt.Printf.

      While other languages favor aliasing a package for ease of use later in the program, Go does not. For instance, aliasing the fmt package to f would not be consistent with the style guide.

      When renaming imports to avoid a name collision, you should aim to rename the most local or project specific import. For instance, if you had a local package called strings, and you also needed to import the system package called strings, you would favor renaming your local package over the system package. Whenever possible, it’s best to avoid name collision altogether.

      In this section, we learned how we can alias an import to avoid colliding with another import in our program. It is important to remember that readability and clarity of your program is important, so you should only use aliasing to make the code more readable or when you need to avoid a naming collision.

      Formatting Imports

      By formatting imports, you can sort the packages into a specific order that will make your code more consistent. Additionally, this will prevent random commits from taking place when the only thing that changes is the sort order of the imports. Since formatting imports will prevent random commits, this will prevent unnecessary code churn and confusing code reviews.

      Most editors will format imports for you automatically, or will let you configure your editor to use goimports. It is considered standard practice to use goimports in your editor, as trying to manually maintain the sort order of your imports can be tedious and prone to errors. Additionally, if any style changes are made, goimports will be updated to reflect those style changes. This ensures that you, and anyone that works on your code, will have consistent styling in your import blocks.

      Here is what an example import block may look like before formatting:

      import (
        "fmt"
        "os"
        "github.com/digital/ocean/godo"
        "github.com/sammy/foo"
        "math/rand"
        "github.com/sammy/bar"
      )
      

      Running the goimport tool (or with most editors that have it installed, saving the file will run it for you), you will now have the following format:

      import (
        "fmt"
        "math/rand"
        "os"
      
        "github.com/sammy/foo"
        "github.com/sammy/bar"
      
        "github.com/digital/ocean/godo"
      )
      

      Notice that it groups all standard library packages first and then groups third party packages together with blank lines. This makes is easier to read and understand what packages are being used.

      In this section we learned that using goimports will keep all of our import blocks properly formatted, and prevent unnecessary code churn between developers working on the same files.

      Conclusion

      When we import packages we’re able to call functions that are not built in to Go. Some packages are part of the standard library that installs with Go, and some we will install through go get.

      Making use of packages allows us to make our programs more robust and powerful as we’re leveraging existing code. We can also create our own packages for ourselves and for other programmers to use in future programs.



      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

      How to Install R Packages using devtools on Ubuntu 18.04


      Introduction

      A popular open-source programming language, R specializes in statistical computing and graphics. It is widely used for developing statistical software and performing data analysis. The R community is known for continuously adding user-generated packages for specific areas of study, which makes it applicable to many fields.

      In this tutorial, we’ll go over how to install devtools and use it to install an R package directly from GitHub.

      Prerequisites

      To follow along with this tutorial, you will need an Ubuntu 18.04 server with:

      Once these prerequisites are in place, you’re ready to begin.

      We’ll be installing devtools from the interactive shell, but before we do, we’ll need to install these system dependencies:

      • sudo apt install build-essential libcurl4-gnutls-dev libxml2-dev libssl-dev

      With these dependencies in place, we’re ready to continue.

      Through devtools we’ll be able to install and build packages directly from GitHub, BitBucket, local files, and install specific versions from CRAN. To make devtools available system-wide, we’ll enter R’s shell as root:

      From within the monitor, we’ll use the install.packages() function to install devtools from the official Comprehensive R Archive Network (CRAN).

      • install.packages('devtools')

      Installation may take a while. When it’s finished, near the end of the installation output, we should see:

      Output

      ... ** testing if installed package can be loaded * DONE (devtools)

      Next, we’ll put it to the test as we fetch and build a project directly from GitHub.

      Step 3 — Installing an R Package from GitHub

      In this step, we’re going to install the latest development build of Shiny, a web application framework for R, directly from GitHub. We’ll do this using the install_github function provided by devtools. A GitHub package is defined by its author (rstudio) and its name (shiny) which you can find from the GitHub URL of the main project page: https://github.com/rstudio/shiny.

      Use the following command to install:

      • devtools::install_github('rstudio/shiny')

      Installation has successfully completed when we see the following lines near the end of the output and are returned to the R prompt:

      Output

      . . . ** testing if installed package can be loaded * DONE (shiny) >

      We can see the specific version of Shiny we’ve installed with the following command:

      Output

      [1] ‘1.1.0.9000’

      In the next step, we'll take a quick look at Shiny. We’ll need to do a couple of system-level tasks first, so we’ll exit the monitor with the following command or by using CTRL-D.:

      Either of these will prompt you to save your workspace image, R’s working environment that includes user-defined objects. This isn’t necessary for our purposes, so you can safely enter n.

      Since we’ll be using a web browser to look at an example of what Shiny can do, we’re going to make sure that web traffic is allowed.

      Check the Firewall

      Shiny is a web application framework, so in order to view its examples in a browser, we’ll need to ensure that web traffic is allowed on our firewall. The built-in web server randomly chooses a port each time it is started unless we initiate it with a specific value. In order to make firewall management easier, we’ll specify port 4040 when we run our example.

      Let’s check the status of the firewall, if we have it enabled:

      If you followed our prerequisite tutorials, only SSH is allowed, as indicated in the following output:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6)

      You may have other rules in place or no firewall rules at all. Since only SSH traffic is permitted in this case, we’ll add port 4040 and check the status when we’re done.

      • sudo ufw allow 4040/tcp
      • sudo ufw status

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 4040/tcp ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 4040/tcp (v6) ALLOW Anywhere (v6)

      With the firewall configured, we’re ready to take a look at Shiny.

      Run Shiny:

      We’ll connect to R, this time as a regular user. Be sure to type R as title case.

      Next, we’ll load the Shiny package:

      Shiny includes eleven built-in examples that demonstrate how it works. We’ll load the library, then run the first example. Because we are working on a remote server, we’ll specify the host address in order to browse from our local machine. We’ll also set launch.browser to FALSE so it doesn’t try to launch a browser on the remote server.

      • runExample("01_hello", host = "203.0.113.0", port = 4040, launch.browser= FALSE)

      Output

      Listening on http://203.0.113.0:4040

      Let’s visit this URL in a web browser:

      Screenhot of Shiny's 01-Hello example

      We installed Shiny to illustrate using devtools to install directly from a GitHub repository. Then we ran the example Shiny application without elevated privileges to verify that all users have access to the package.

      Reinstalling the Stable Version of Shiny

      For a production situation, we would install from CRAN unless we had a compelling reason to install from the repository.

      Let’s take a moment to return to the stable package. First, we’ll interrupt the server with CTRL + C, then exit the R shell with CTRL + D and re-enter it as root:

      We can install the stable version with the following command, which will overwrite the installation from GitHub that we completed in the earlier step.

      • install.packages("shiny")

      Let’s verify the change in version:

      Output

      [1] ‘1.1.0’

      The output indicates that instead of 1.1.0.9000, the version we installed from GitHub, we’re now running the stable release.

      Note: We can also find out more information about a package’s version from the system command line from its DESCRIPTION file.

      • cat /usr/local/lib/R/site-library/shiny/DESCRIPTION

      Conclusion

      In this tutorial, we’ve installed the latest Shiny package directly from GitHub and learned how to reinstall its stable release from CRAN.

      If you’re interested in learning more about Shiny itself, you can take a look at RStudio’s Shiny tutorial. You may also be interested in installing the open source RStudio Server, an interface to a version of R running on a remote Linux server, which brings an IDE to a server-based deployment.



      Source link