Introduction
Go is a programming language that is open source and designed to make programmers more productive. It was created at Google in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson, who wanted a language that was fast, simple, reliable, and scalable. Some of the key features of Go include:
download go 1.20.1
Download File: https://urluso.com/2vuPea
Support for environment adopting patterns similar to dynamic languages
Fast compilation time
Inbuilt concurrency support: lightweight processes (via goroutines), channels, select statement
Simplicity
Powerful standard library
Testing support
Powerful compiler
Go binaries
Go has been used by many organizations in every industry to power their software and services. Some examples of famous projects that use Go are Docker, Kubernetes, Terraform, Hugo, and gRPC. You can find more stories of companies using Go .
Download and install Go
To compile and run a simple program in Go, you need to download and install the latest version of Go from the . The installation process is different for different operating systems. Here are the steps for Linux, Mac, and Windows:
Linux
Remove any previous Go installation by deleting the /usr/local/go folder (if it exists), then extract the archive you just downloaded into /usr/local, creating a fresh Go tree in /usr/local/go:$ rm -rf /usr/local/go && tar -C /usr/local -xzf go1.20.4.linux-amd64.tar.gz(You may need to run the command as root or through sudo).
Add /usr/local/go/bin to the PATH environment variable. You can do this by adding the following line to your $HOME/.profile or /etc/profile (for a system-wide installation):export PATH=$PATH:/usr/local/go/binNote: Changes made to a profile file may not apply until the next time you log into your computer. To apply the changes immediately, just run the shell commands directly or execute them from the profile using a command such as source $HOME/.profile.
Verify that you've installed Go by opening a command prompt and typing the following command:$ go versionConfirm that the command prints the installed version of Go.
Mac
Open the package file you downloaded and follow the prompts to install Go.The package installs the Go distribution in /usr/local/go. The package should put the /usr/local/go/bin directory in your PATH environment variable. You may need to restart any open Terminal sessions for the change to take effect.
Verify that you've installed Go by opening a terminal and typing the following command:$ go versionConfirm that the command prints the installed version of Go.
Windows
Open the MSI file you downloaded and follow the prompts to install Go.The installer should put the C:\Go\bin directory in your PATH environment variable. You may need to restart any open command prompts for the change to take effect.
Verify that you've installed Go by opening a command prompt and typing the following command:C:\> go versionConfirm that the command prints the installed version of Go.
Write some code in Go
Now that you have Go installed, you can write some code in Go. Go programs are organized into packages, which are collections of source files that share a common namespace and a set of dependencies. A package can be executable or a library. An executable package must have a file called main.go that defines a function called main(), which is the entry point of the program. A library package can be imported by other packages to use its exported identifiers, such as types, variables, constants, and functions.
Hello, world!
Let's start with a simple program that prints "Hello, world!" to the standard output. Create a folder called hello and inside it create a file called main.go. Then write the following code in the file:
package main import "fmt" func main() fmt.Println("Hello, world!")
The first line of the code declares the package name, which is main in this case. The second line imports the fmt package from the standard library, which provides formatted I/O functions. The third line defines the main() function, which prints "Hello, world!" using the fmt.Println() function.
To run the program, open a terminal or command prompt and navigate to the hello folder. Then type the following command:
$ go run main.go
You should see the output "Hello, world!" on your screen.
Call code in an external package
You can use code from other packages by importing them in your program. For example, you can use the package to generate random numbers. Let's modify our program to print a random number between 1 and 10 instead of "Hello, world!". Edit your main.go file and change it to:
package main import ( "fmt" "math/rand" "time" ) func main() // Seed the random number generator with the current time rand.Seed(time.Now().UnixNano()) // Generate a random number between 1 and 10 n := rand.Intn(10) + 1 // Print the number fmt.Println(n)
The first line of the code is unchanged, it still declares the package name as main. The second line imports three packages: . We use parentheses to group multiple imports into one statement. The third line defines the main() function, which does three things:
How to download and install go 1.20.1 on Windows
Download go 1.20.1 source code and build from scratch
Go 1.20.1 release notes and new features
Download go 1.20.1 for Linux and Mac OS
Go 1.20.1 installation instructions and troubleshooting
Download go 1.20.1 for FreeBSD, Linux ppc64le, and Linux s390x
Go 1.20.1 binary distributions and checksums
Download go 1.20.1 for ARM64 and x86-64 processors
Go 1.20.1 module mirror and checksum database
Download go 1.20.1 for web development and cloud computing
Go 1.20.1 documentation and tutorials
Download go 1.20.1 for data science and machine learning
Go 1.20.1 performance improvements and benchmarks
Download go 1.20.1 for mobile development and cross-platform apps
Go 1.20.1 compatibility and migration guide
Download go 1.20.4, the latest stable version of go
Go 1.20.4 vs go 1.20.3 vs go 1.20.2 vs go 1.20.1 comparison
Download go 2, the upcoming major version of go
Go 2 features and roadmap
Download go playground, an online tool to run go code
Go playground examples and tips
Download go tools, a collection of tools for working with go code
Go tools usage and best practices
Download go packages, a repository of reusable go code
Go packages overview and search
Download go vet, a tool to check the correctness of go code
Go vet errors and warnings
Download go fmt, a tool to format go code according to the official style guide
Go fmt options and flags
Download go test, a tool to run automated tests for go code
Go test coverage and reports
Download go mod, a tool to manage dependencies for go modules
Go mod commands and configuration
Download go run, a tool to compile and run go code without building an executable file
Go run arguments and environment variables
Download golang.org/x, a subrepository of experimental and deprecated packages for go
Golang.org/x packages list and status
Download gopls, a language server for go that provides IDE features such as code completion, diagnostics, formatting, etc.
Gopls installation and integration with editors
Download gopherjs, a compiler that transpiles go code to JavaScript code that can run in the browser
Gopherjs examples and limitations
Download gomobile, a tool that enables cross-platform mobile development with go
Gomobile bind and init commands
Download gophercises, a series of exercises that help you learn go by building real-world applications
Gophercises solutions and feedback
Download gotour, an interactive introduction to the go programming language
Gotour slides and exercises
It calls the , which returns the current time in nanoseconds. This is necessary to initialize the random number generator with a different seed every time we run the program, otherwise we would get the same sequence of random numbers every time.
It calls the function with the argument 10, which returns a random integer between 0 and 9. We add 1 to this result to get a number between 1 and 10.
It calls the function with the argument n, which prints the number to the standard output.
To run the program, open a terminal or command prompt and navigate to the hello folder. Then type the same command as before:
$ go run main.go
You should see a random number between 1 and 10 on your screen. Try running the program multiple times and see how the output changes.
Write more code in Go
Now that you know how to write and run a simple program in Go, let's write some more code in Go. Go has many features and constructs that make it easy and fun to write code. Some of them are:
Data types: Go has basic data types such as numbers, strings, booleans, and arrays, as well as composite data types such as structs, slices, maps, and interfaces.
Variables: Go has a simple and concise syntax for declaring and assigning variables. You can use the var keyword or the short declaration operator :=.
Constants: Go has constants that are declared with the const keyword and cannot be changed.
Functions: Go has functions that are declared with the func keyword and can have zero or more parameters and return values. You can also define anonymous functions and assign them to variables or pass them as arguments to other functions.
Control structures: Go has control structures such as if, else, switch, for, and defer that allow you to control the flow of your program.
Error handling: Go has a built-in error type that is returned by functions that can fail. You can use the error value to check for errors and handle them accordingly.
Goroutines and channels: Go has concurrency features that allow you to run multiple tasks simultaneously and communicate between them. You can use the go keyword to launch a function as a goroutine, which is a lightweight thread of execution. You can use channels to send and receive values between goroutines.
A simple calculator
To demonstrate some of these features, let's write a simple calculator program that performs basic arithmetic operations on two numbers. Create a folder called calc and inside it create a file called main.go. Then write the following code in the file:
// A simple calculator program in Go package main import ( "fmt" "os" "strconv" ) // A function that takes two numbers and an operator as strings // and returns the result of the operation as a float64 func calculate(num1, num2, op string) (float64, error) err2 != nil return 0, fmt.Errorf("invalid numbers: %s and %s", num1, num2) // Perform the operation based on the operator switch op case "+": return n1 + n2, nil case "-": return n1 - n2, nil case "*": return n1 * n2, nil case "/": // Check for division by zero if n2 == 0 return 0, fmt.Errorf("division by zero") return n1 / n2, nil default: // Return an error for invalid operator return 0, fmt.Errorf("invalid operator: %s", op) func main() // Check if the number of arguments is correct if len(os.Args) != 4 fmt.Println("Usage: calc num1 op num2") os.Exit(1) // Get the arguments from the command line num1 := os.Args[1] op := os.Args[2] num2 := os.Args[3] // Call the calculate function with the arguments result, err := calculate(num1, num2, op) // Check for errors in calculation if err != nil fmt.Println("Error:", err) os.Exit(1) // Print the result fmt.Println(result)
The first line of the code is a comment that describes the program. Comments in Go start with // and are ignored by the compiler. The second line declares the package name as main. The third line imports three packages: . The fmt package provides formatted I/O functions, the os package provides access to operating system functionality, and the strconv package provides conversions to and from string representations of basic data types.
The next block of code defines a function called calculate that takes two numbers and an operator as strings and returns the result of the operation as a float64. The function also returns an error value that indicates whether the calculation was successful or not. The function uses the strconv.ParseFloat() function to convert the numbers from strings to float64s, and checks for errors in parsing. Then it uses a switch statement to perform the operation based on the operator, and checks for division by zero. If the operator is invalid, it returns an error with a message.
The last block of code defines the main() function, which is the entry point of the program. The function uses the os.Args slice to get the arguments from the command line, and checks if the number of arguments is correct. Then it calls the calculate() function with the arguments, and checks for errors in calculation. If there is no error, it prints the result using the fmt.Println() function.
To run the program, open a terminal or command prompt and navigate to the calc folder. Then type a command like this:
$ go run main.go 12 + 34
You should see the output 46 on your screen. You can try different numbers and operators and see how the output changes.
Use the go command
The is a tool that you can use to manage your Go code and dependencies. It has many subcommands that perform different tasks, such as:
: compiles your code and produces an executable file.
: compiles and runs your code without producing an executable file.
: runs tests for your code using files that end with _test.go.
: compiles your code and installs the executable file in a specified directory.
: manages modules, which are collections of packages that can be versioned and distributed.
: shows documentation for a package or a symbol within a package.
: formats your code according to a standard style.
: checks your code for common errors and potential bugs.
: lists information about packages.
: downloads and installs packages from remote repositories.
You can use these subcommands by typing go followed by the subcommand name and any arguments or flags. For example, to build your calculator program, you can type:
$ go build main.go
This will produce an executable file called main (or main.exe on Windows) in the same directory as your source file. You can run this file by typing:
$ ./main 12 + 34
You should see the same output as before.
<h1 Use the Go package discovery tool
One of the great things about Go is that it has a large and active community of developers who create and share packages that you can use in your own code. There are thousands of packages available for various purposes, such as web development, data processing, cryptography, testing, logging, and more. You can find these packages by using the , which is a website that lets you search for and explore packages from the Go ecosystem.
To use the tool, you can visit the website and type a keyword or a package name in the search box. You can also browse by categories, such as web, database, machine learning, etc. For each package, you can see information such as its name, description, import path, license, documentation, examples, and source code. You can also see how many other packages depend on it, and how many stars it has on GitHub.
For example, if you want to find a package that provides HTTP client and server functionality, you can type http in the search box and see a list of packages that match your query. One of them is the package from the standard library, which is the most widely used package for HTTP communication in Go. You can click on it and see its documentation and examples. You can also see that it has over 1000 dependent packages and over 1000 stars on GitHub.
To use a package in your code, you need to import it using its import path. For example, to use the net/http package, you need to add this line to your code:
import "net/http"
Then you can use the exported identifiers from the package, such as types, variables, constants, and functions. For example, to create a simple web server that responds with "Hello, world!" to any request, you can write this code:
package main import ( "fmt" "net/http" ) func main() // Define a handler function that writes "Hello, world!" to the response handler := func(w http.ResponseWriter, r *http.Request) fmt.Fprintln(w, "Hello, world!") // Register the handler function for the root path http.HandleFunc("/", handler) // Start listening for HTTP requests on port 8080 http.ListenAndServe(":8080", nil)
To run this program, open a terminal or command prompt and navigate to the folder where you saved the code. Then type:
$ go run main.go
This will start the web server on port 8080. You can open a browser and visit and see the message "Hello, world!" on your screen.
Conclusion
In this article, you learned how to download and install Go, how to write some simple code in Go, and how to use some of the tools and libraries that Go provides. You also learned how to use the go command to manage your code and dependencies, and how to use the Go package discovery tool to find packages you can use in your own code. You saw some examples of how Go makes programming easy and fun.
Go is a powerful and versatile language that can help you create fast, reliable, and scalable software. It has many features and benefits that make it a great choice for web development, cloud and network services, devops and site reliability, command-line interfaces, and more. It also has a large and active community of developers who create and share packages that you can use in your own code.
If you want to learn more about Go, here are some resources that you can check out:
: The official website of Go, where you can find documentation, tutorials, blog posts, videos, podcasts, and more.
: An interactive tutorial that teaches you the basics of Go through a series of exercises.
: A document that gives tips on how to write clear and idiomatic Go code.
: A website that shows how to use various features of Go through annotated example programs.
: An online tool that lets you write and run Go code in your browser.
: A comprehensive online course that covers everything you need to know about Go, from the basics to advanced topics.
FAQs
Here are some frequently asked questions about Go:
What is the difference between Go and Golang?
Go and Golang are two names for the same programming language. Go is the official name of the language, but Golang is often used as an alternative name, especially in online searches, to avoid confusion with other terms that also mean "go". For example, if you search for "go tutorial" on Google, you might get results about the board game Go, the verb go, or the Go programming language. But if you search for "golang tutorial", you will only get results about the programming language.
Is Go a compiled or interpreted language?
Go is a compiled language, which means that the source code is translated into executable code by a compiler before it can be run. This makes Go programs faster and more efficient than interpreted languages, which execute the source code directly without compiling it. However, Go also has some features that make it feel like an interpreted language, such as fast compilation time, dynamic typing, and interactive development.
Is Go an object-oriented language?
Go is not a traditional object-oriented language, which means that it does not have classes, inheritance, or constructors. However, Go does have some features that support object-oriented programming, such as structs, methods, interfaces, and embedding. Structs are data structures that can have fields and methods. Methods are functions that are associated with a specific type. Interfaces are abstract types that define a set of methods. Embedding is a way of composing structs from other structs or interfaces.
Is Go a functional language?
Go is not a pure functional language, which means that it does not enforce immutability, recursion, or higher-order functions. However, Go does have some features that support functional programming, such as first-class functions, closures, and multiple return values. First-class functions are functions that can be assigned to variables or passed as arguments to other functions. Closures are functions that can access variables from their outer scope. Multiple return values are functions that can return more than one value.
Is Go a low-level or high-level language?
Go is neither a low-level nor a high-level language, but rather a middle-level language. This means that it has some features that make it closer to the hardware, such as pointers, memory management, and concurrency primitives. But it also has some features that make it closer to the developer, such as garbage collection, error handling, and testing support. This makes Go a good choice for writing programs that need both performance and productivity.
44f88ac181
Commentaires