Golang is a programming language that has attracted much attention in recent years. Its advantages such as simple syntax, excellent performance, and strong concurrency capabilities have become more and more known. But for programmers who are new to golang, how to run their own code is a basic issue that needs to be understood. This article will introduce the environment installation and basic operation methods of golang.
1. Environment installation
First, we need to install the golang environment locally. The golang official website provides the download address: https://golang.org/dl/. We can download the corresponding version of the installation package according to our own operating system. After the installation is complete, we need to set the environment variables. For Windows systems, you can add GOPATH in System Properties-Advanced System Settings-Environment Variables, and the value is the path to your working directory. For Unix systems, environment variables can be added in the .bashrc or .zshrc file.
2. Write code
After installing the golang environment, we can start writing golang code. Generally speaking, the file extension of golang source code is .go. For example, we can create a new hello.go file and enter the following code:
package main import "fmt" func main() { fmt.Println("Hello, world!") }
3. Run the code
After writing the code, we need to enter the directory where the code is located on the command line. Then, you can run it with the following command:
go run hello.go
At this point, we should see "Hello, world!" output in the terminal. Careful readers may have noticed that we did not compile the code, but ran it directly using the "go run" command. In golang, the go run command can compile and run go source files.
Sometimes we need to compile the file before running it. At this time, you can use the following commands:
go build hello.go ./hello
After compilation, an executable binary file will be generated. We only need to use "./" to run it.
4. Summary
Through the above three steps, we successfully ran our first golang program. In golang, developers can use simple commands to write, compile and run programs, which is one of the reasons why golang is widely used. Next, we can slowly and deeply learn about golang's various data types, concurrency, network programming, etc., and enjoy the efficient programming experience brought by golang.
The above is the detailed content of How to run code in golang. For more information, please follow other related articles on the PHP Chinese website!