Your First Go Program

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

  1. Open a terminal or command prompt.
  2. Create a directory for your first project:
    mkdir -p $GOPATH/src/hello
    

Step 2: Create a Go File

  1. Navigate to the project directory:
    cd $GOPATH/src/hello
    
  2. 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

  1. Open the hello.go file in your text editor.
  2. Write the following code:
    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("Hello, World!")
    }
    

Step 4: Run the Program

  1. Open a terminal or command prompt in the hello directory.
  2. Run the program using the following command:
    go run hello.go
    
  3. You should see the output:
    Hello, World!
    

Step 5: Build the Program

  1. To create an executable file, use the go build command:
    go build hello.go
    
  2. This will generate an executable file named hello (or hello.exe on Windows) in the same directory.
  3. Run the executable file:
    • On Windows:
      hello.exe
      
    • On macOS and Linux:
      ./hello
      
  4. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top