DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

How can I 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:

  1. Installation
    If you haven't installed Go (often referred to as "Golang"), visit the official Go website for installation instructions: https://golang.org/doc/install

  2. Writing the Code
    Create a new file called hello.go using your favorite text editor and enter the following code:

   package main

   import "fmt"

   func main() {
       fmt.Println("Hello, world!")
   }
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:

    • package main: This defines the package name of your program. Every Go executable program starts with the main package.
    • import "fmt": This includes the fmt package, which contains functions for formatting and printing strings.
    • func main(): The main() function is the entry point of the program. When you run the program, this is the first function that gets executed.
  2. Running the Code:
    Navigate to the directory containing your hello.go file in your terminal or command prompt, then type the following command:

   go run hello.go
Enter fullscreen mode Exit fullscreen mode

After running the above command, you should see the output:

   Hello, world!
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

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/

Top comments (0)