Now that you have set up the Go environment on your computer, you are ready to write and run your first Go program. Follow these simple steps to create a basic "Hello, World!" program.
Step 1: Create a Project Directory
- Open a terminal or command prompt.
- Create a directory for your first project:
mkdir -p $GOPATH/src/hello
Step 2: Create a Go File
- Navigate to the project directory:
cd $GOPATH/src/hello
- Create a file named
hello.go
using a text editor. You can use any text editor you like, such as Visual Studio Code, Sublime Text, or even a simple editor like Notepad or Nano.
Step 3: Write the Go Code
- Open the
hello.go
file in your text editor. - Write the following code:
package main import "fmt" func main() { fmt.Println("Hello, World!") }
Step 4: Run the Program
- Open a terminal or command prompt in the
hello
directory. - Run the program using the following command:
go run hello.go
- You should see the output:
Hello, World!
Step 5: Build the Program
- To create an executable file, use the
go build
command:go build hello.go
- This will generate an executable file named
hello
(orhello.exe
on Windows) in the same directory. - Run the executable file:
- On Windows:
hello.exe
- On macOS and Linux:
./hello
- On Windows:
- You should see the same output:
Hello, World!
Conclusion
Congratulations! You have successfully created and run your first Go program. This simple "Hello, World!" example is your first step into the world of Go programming. From here, you can explore more features and start building more complex applications.