• Tidak ada hasil yang ditemukan

how-to-code-in-go.pdf

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Membagikan "how-to-code-in-go.pdf"

Copied!
447
0
0

Teks penuh

We recommend that you start with a clean, fresh server to start learning how to program with Go. This book begins with chapters on how to set up and configure a local Go development environment.

Setting Up Go

You need a computer or virtual machine with Ubuntu 18.04 installed, as well as administrative access to that machine and an Internet connection. Note: Although /usr/local/go is the officially recommended location, some users may prefer or require other paths.

Creating Your Go Workspace

This will secure all files and ensure that only the root user can run the Go binaries. The default directory for the Go workspace since version 1.8 is your user's home directory with a subdirectory of go or $HOME/go.

Creating a Simple Program

This code will use the fmt package and call the Println function with Hello, World.

Opening and Configuring PowerShell

You will complete most of the installation and configuration in a command line interface, which is a non-graphical way to interact with your computer. When the options appear, right-click Windows PowerShell from the Desktop application.

PowerShell

RemoteSigned will allow you to run scripts and configuration files downloaded from the Internet that are signed by trusted publishers, again opening your device to vulnerabilities if those trusted scripts are actually malicious. In this case, a digital signature is not required, so you can open your computer to the risk of running unsigned and potentially malicious scripts downloaded from the Internet.

Installing the Package Manager Chocolatey

If you look at the output, you can recognize the DownloadString method used to display the script and signature in the PowerShell window. This will pass the script to iex or the Invoke-Expression cmdlet, which will execute the contents of the script and run the installation for the Chocolatey package manager.

Installing the Text Editor Nano (Optional)

Installing Go

Creating Your Go Workspace

You'll see directories like github.com or golang.org when your program imports third-party libraries. Canonical imports are imports that refer to a fully qualified package, such as github.com/digitalocean/godo.

Creating a Simple Program

However, to make the program more interesting, apply the traditional "Hello, World!" program so that it asks the user for his name. When you're done with the tutorial, you'll have a program that looks like this when you run it:.

Sammy

Writing the Basic “Hello, World!” Program

You follow the fmt.Println function through a sequence of characters, such as "Hello, World!", enclosed in quotes. The fmt.Println function prints this string on the screen when the program is run.

Running a Go Program

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. Instead, it tells the Go compiler that the package should be compiled as an executable package.

Prompting for User Input

Go applications require the main package and exactly one main() function that serves as the entry point for the application. Use the fmt.Println function again to print the text to the screen.

This time, instead of using the fmt.Println method, use fmt.Printf again. The program recorded all of our keystrokes, including the ENTER key we pressed to continue the program.

In Go, we can define a variable with the var keyword, followed by the variable name and the desired data type. Arrays are defined by declaring the size of the array and then the data type with the values ​​defined in curly braces. This tutorial covered the basics of working with the string data type in the Go programming language.

In this tutorial, we'll go over a few different functions that we can use to work with strings in Go. The strings.Join, strings.Split, and strings.ReplaceAll functions are some additional ways to manipulate strings in Go. Using the string function strings.Join, strings.Split and strings.ReplaceAll will give you greater control to manipulate strings in Go.

This tutorial will review the operators that can be used with numeric data types in Go. In Go, we can use the plus and minus signs as one element in a value pair to: return the identity of the value (+) or change the sign of the value.

By using key-value pairs in map data types, you can reference the keys to get the values. After the data type, you can declare the individual values ​​of the array elements in curly braces. By using index numbers to define start and end points, you can call a subsection of values ​​within an array.

We used the errors.New function from the standard library to create a new error message with the string "barnacles" as the error message. We used the fmt.Errorf function to create an error message that would include the current time. Similar to the previous example, we combine our error message with a short prefix and print the result to standard output using the fmt.Println function.

The formatting string we supplied to fmt.Errorf contains the %v formatting directive that tells fmt.Errorf to use the default formatting for the first argument supplied after the formatting string. Typically, you will not see an error created like this to be immediately used for no other purpose, as in the previous example. In practice, it is much more common to create an error and return it from a function when something goes wrong.

For example, a capitalized function that returns a string and an error would be declared using func capitalize(name string) (string, error). We define capitalize() as a function that takes a string (the name to be capitalized) and returns a string and an error value. The uppercase function will return an error when callers of the function specify an empty string for the name parameter.

Reducing boilerplate

When the name parameter is not the empty string, capitalize() uses strings.ToTitle to capitalize the name parameter and returns zero for the error value. Using this we can then return any errors encountered in uppercase by using the return statement in front of the call to handle with the error as a parameter. At the same time, we assign the error returned with capital to the error variable.

Go provides two ways to generate errors in the standard library, errors.New and fmt.Errorf. To pass this more complex error information and achieve more functionality, we can implement the standard error interface type library. By implementing this method, we can convert any type we define into its own error.

Since sayHello will always return an error, the call to fmt.Println inside the body of the if statement in main() will always execute. We then use fmt.Println to print a short string prefixed with "unexpected error:" along with the MyError instance located in the err variable. Note that we don't need to call Error() directly, as the fmt package can automatically detect that this is an error implementation.

Within the RequestError method Error() we use the fmt.Sprintf function to construct a string using the information provided when the error was created. The error interface only exposes one method, but we may need to access the other methods for error implementations to properly handle an error. For example, we can have multiple custom implementations of errors that are temporary and can be retried - indicated by the presence of a Temporary() method.

The error messages from these errors do not help anyone find the cause of the error. When the Error() method is called, we again use fmt.Sprintf to print the context message, then on error (fmt.Sprintf also implicitly calls the Error() method). Inside main() we create an error using errors.New and then wrap that error using the wrap function we defined.

In our next article in the error handling series, we'll explore panic—what it is and how to deal with it. The error interface that we covered in our previous two articles on error handling largely deals with errors that we expect while writing Go programs. The error interface even allows us to recognize the rare possibility of an error occurring through function calls, so we can react appropriately in those situations.

Out of Bounds Panics

The name of the panic's output gives a hint: panic: runtime error: index out of range. The message that is produced contains several pieces of information that are useful in diagnosing the cause of the panic. The panic in the previous example was generated by an out-of-bounds entry to a cut.

Since the s variable is zero, when the SayHello function is called, it tries to access the Name field at. Although in this case we explicitly set s to zero, in practice this happens less obviously. Whenever possible, it is a best practice to try to return error values ​​to users of our package.

Inside the body of our main function, we create a new instance of this Shark structure and request a pointer to it with the & operator. Because it's a pointer receiver, and the receiver in this case is null, it panics because it can't recognize a null pointer. It takes a single string as an argument, which is the message that will produce the panic.

Here we define a function foo that calls the built-in panic with the string "oh no!". By comparing the error variable to nil, we can detect if a panic occurred, in which case we log the panic using the log.Println function as if it were any other error. Since the argument to the panic function is an empty interface, it can be any type.

The err value returned from recover() is exactly the value that was passed to the panic() call. If it is, it will create a panic using the builtin panic with a null argument. This silent behavior is why it is very important to ensure that the argument of the builtin panic function is not null.

To make use of the functions of a package, you must access the package with an import statement. An import statement consists of the import keyword along with the name of the package. To make use of the extra package, we can now format the output and print the iteration on which each random number was generated during loop:.

Next, let's see how to install and use packages that are written by other developers. While the standard library ships with many excellent and useful packages, they are intentionally designed to be general purpose rather than specific in nature. This allows developers to build their own packages on top of the standard library for their specific needs.

Referensi

Dokumen terkait

Khan Department of Statistics and Operations Research Aligarh Muslim University, Aligarh–202 002, India summary Some recurrence relations between expectation of function on single