How to write my first program in Go
Writing a "Hello World" program is a traditional way to start with a new programming language. Here's how you can write and run a "Hello World" program in Go:
Installation
If you haven't installed Go (often referred to as "Golang"), visit the official Go website for installation instructions: https://golang.org/doc/installWriting the Code
Create a new file calledhello.go
using your favorite text editor and enter the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
Explanation:
package main
: This defines the package name of your program. Every Go executable program starts with themain
package.import "fmt"
: This includes thefmt
package, which contains functions for formatting and printing strings.func main()
: Themain()
function is the entry point of the program. When you run the program, this is the first function that gets executed.
Running the Code:
Navigate to the directory containing yourhello.go
file in your terminal or command prompt, then type the following command:
go run hello.go
After running the above command, you should see the output:
Hello, world!
- Building the Code (Optional): If you want to compile the code into a binary instead of just running it, you can use the following command:
go build hello.go
This will produce an executable in the current directory (e.g., hello.exe
on Windows or just hello
on macOS/Linux). You can then run this executable directly to see the output.
Congratulations! You've just written and run your first program in Go.
Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects and learning golang. I am currently seeking a remote job or internship.
Twitter: https://twitter.com/Diwakar_766
GitHub: https://github.com/DIWAKARKASHYAP
Portfolio: https://diwakar-portfolio.vercel.app/
Subscribe to my newsletter
Read articles from Diwakar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Diwakar
Diwakar
As a passionate developer, I thrive on acquiring new knowledge. My journey began with web development, and I am now actively engaged in open source contributions, aiding individuals and businesses.