How to Write A Simple "Hello World" Program In Golang?

12 minutes read

To write a simple "Hello World" program in Golang, you need to follow these steps:

  1. Create a new file with a ".go" extension, for example, "hello.go".
  2. Start by importing the required module for printing to the console using the "fmt" package. Add the following line at the beginning of the file: import "fmt"
  3. Define the main function, which is the entry point for execution in a Go program. Use the following syntax: func main() { // Your code goes here }
  4. Within the main function, use the "Println" function from the "fmt" package to print the message "Hello, World!" to the console. Add the following line: fmt.Println("Hello, World!")
  5. Save the file.
  6. Open your command prompt or terminal and navigate to the directory where you saved the "hello.go" file.
  7. Compile the Go program into an executable by running the following command: go build hello.go
  8. After successful compilation, an executable file named "hello" or "hello.exe" (depending on your operating system) will be generated in the same directory.
  9. Finally, run the program by entering the name of the executable file in the command prompt or terminal: ./hello The output will be: Hello, World!


That's it! You have written and executed a simple "Hello World" program in Go.

Best Golang Books to Read in 2024

1
Go Programming Language, The (Addison-Wesley Professional Computing Series)

Rating is 5 out of 5

Go Programming Language, The (Addison-Wesley Professional Computing Series)

2
Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

Rating is 4.9 out of 5

Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

3
Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

Rating is 4.8 out of 5

Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

4
Hands-on Go Programming : Learn Google’s Golang Programming, Data Structures, Error Handling and Concurrency ( English Edition): Learn Google's Golang ... Handling and Concurrency ( English Edition)

Rating is 4.7 out of 5

Hands-on Go Programming : Learn Google’s Golang Programming, Data Structures, Error Handling and Concurrency ( English Edition): Learn Google's Golang ... Handling and Concurrency ( English Edition)

5
Learn Data Structures and Algorithms with Golang: Level up your Go programming skills to develop faster and more efficient code

Rating is 4.6 out of 5

Learn Data Structures and Algorithms with Golang: Level up your Go programming skills to develop faster and more efficient code

6
Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

Rating is 4.5 out of 5

Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

7
Hands-On Software Engineering with Golang: Move beyond basic programming to design and build reliable software with clean code

Rating is 4.4 out of 5

Hands-On Software Engineering with Golang: Move beyond basic programming to design and build reliable software with clean code


How to import the fmt package in a Golang program?

In a Golang program, you can import the fmt package using the import keyword followed by the package name.


Here's an example:

1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}


In the above example, the fmt package is imported using the import statement import "fmt". This allows you to use the functions and types provided by the fmt package in your program.


How to use switch statements in Golang?

In Go, you can use the switch statement to select one of many code blocks to be executed based on different conditions. Here's how you can use the switch statement in Go:

  1. Basic Syntax: switch expression { case condition1: // code block to be executed when condition1 is true case condition2: // code block to be executed when condition2 is true ... default: // code block to be executed when none of the conditions is true }
  2. Matching Expressions: The expression in the switch statement can be of any data type: number, string, or boolean.
  3. Switching on a Value: switch value { case 1: // code block to be executed when value is 1 case 2: // code block to be executed when value is 2 ... default: // code block to be executed when none of the conditions is true }
  4. Multiple Values in a Case: You can include multiple values to match in a case: switch value { case 1, 3, 5: // code block to be executed when value is 1, 3, or 5 ... }
  5. Expressionless Switch: If you omit the expression from the switch statement, it is considered an expressionless switch. In this case, you can use boolean conditions in the case statements: switch { case age < 18: fmt.Println("You are a minor") case age >= 18: fmt.Println("You are an adult") }
  6. Type Switch: Go also supports type switching, where you can check the type of an interface value. The syntax is a bit different: switch value.(type) { case int: // code block to be executed when value is of type int case string: // code block to be executed when value is of type string ... }


Note: Unlike other programming languages like C or C++, Go doesn't automatically fall through the cases, unless you explicitly use the fallthrough keyword.


That’s how you can use switch statements in Go to perform different operations based on different conditions.


How to take input from the user in Golang?

To take input from the user in a Go program, you can use the fmt.Scan() or fmt.Scanf() functions. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import "fmt"

func main() {
	var name string
	var age int

	fmt.Println("Enter your name:")
	fmt.Scan(&name)

	fmt.Println("Enter your age:")
	fmt.Scan(&age)

	fmt.Printf("Hello, %s! You are %d years old.", name, age)
}


In this example, we use fmt.Scan() to read the user's input for the name and age. The & operator is used to get the memory address of the variables where we want to store the input values.


After taking the input, the program prints a formatted string using fmt.Printf() to display the name and age values entered by the user.


Note that fmt.Scan() reads input until the first whitespace character, so it is suitable for reading single words or single values. If you want to read multiple values or handle different types of input, you can use fmt.Scanf() with format specifiers. Here's an example using fmt.Scanf():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import "fmt"

func main() {
	var name string
	var age int

	fmt.Println("Enter your name and age:")
	fmt.Scanf("%s %d", &name, &age)

	fmt.Printf("Hello, %s! You are %d years old.", name, age)
}


In this example, fmt.Scanf() is used to read a string followed by an integer value from the user's input, using the format string "%s %d". The format specifier %s is used for a string, and %d is used for an integer.


Remember to include the fmt package using import "fmt" at the beginning of your Go program to have access to the input/output functions.


How to use for loops in Golang?

In Go, a for loop is used to repeatedly execute a block of code until a specific condition is met. The syntax for a for loop in Go is as follows:

1
2
3
for initialisation; condition; post {
    // Code to be executed
}


The initialisation statement is executed only once before the loop starts. It can be used to declare and initialize loop variables.


The condition statement checks whether the loop should continue executing or not. If the condition evaluates to false, the loop terminates.


The post statement is executed after each iteration of the loop. It is commonly used to update loop variables.


Here's an example that demonstrates the usage of a simple for loop in Go:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main

import "fmt"

func main() {
    // Loop from 1 to 5
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }
}


Output:

1
2
3
4
5
1
2
3
4
5


In this example, the loop starts with i initialized to 1. The loop executes as long as i is less than or equal to 5. After each iteration, i is incremented by 1 using the post statement i++.


You can also use for loops without the initialisation and post statements. Here's an example that demonstrates an infinite loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import "fmt"

func main() {
    i := 1
    for {
        fmt.Println(i)
        i++
        if i > 5 {
            break
        }
    }
}


Output:

1
2
3
4
5
1
2
3
4
5


In this example, the for loop doesn't have the initialisation and post statements. Instead, it relies on the break statement to terminate the loop when i becomes greater than 5.


For loops in Go can also be used to iterate over collections like arrays, slices, maps, etc. using the range keyword. This allows you to execute a block of code for each element in the collection.


How to print "Hello World" to the console in Golang?

To print "Hello World" to the console in Golang, you can use the fmt package which provides formatted I/O functions. Here's an example code:

1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}


In this code, we import the fmt package, which includes the Println function. Inside the main function, we use fmt.Println to print the string "Hello World" followed by a newline character to the console.


How to write a basic "Hello World" program in Golang?

To write a basic "Hello World" program in Golang, follow these steps:

  1. Create a new file with the .go extension, such as hello.go.
  2. Open the file in a text editor of your choice.
  3. Write the following code in the file:
1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}


  1. Save the file.
  2. Open a terminal or command prompt and navigate to the directory where the file is saved.
  3. Build the program by executing the following command:
1
go build hello.go


This will generate an executable file named hello.

  1. Run the program by executing the following command:
1
./hello


You should see the output Hello World printed on the console.


Congratulations! You have successfully written and executed a basic "Hello World" program in Golang.

Facebook Twitter LinkedIn Telegram Whatsapp

Related Posts:

Working with databases in Golang involves establishing a connection to the database server, executing queries or database operations, and handling the results. Here are the fundamental steps to work with databases in Golang:Import the necessary packages: To in...
When developing web applications using the Go programming language (Golang), creating and handling routes is a fundamental aspect. Routes define the endpoints of the application that users can access to interact with different parts of the system. Here is an o...
To install Golang on your computer, follow these steps:Go to the official Golang website at golang.org.Click on the &#34;Downloads&#34; tab on the website&#39;s navigation menu.Choose the appropriate installer for your operating system (Windows, macOS, or Linu...
Goroutines are a fundamental feature of concurrency in the Go programming language (Golang). They are lightweight, independent units of execution that allow multiple tasks to run concurrently within a single program. Here&#39;s how you can use goroutines for c...
In Golang, functions are a fundamental feature for organizing and reusing code. They help in encapsulating a piece of code that performs a specific task and can be called from different parts of a program.To create a function in Golang, you use the keyword &#3...
Performing file input/output (I/O) operations in Golang involves a few basic steps. Here is a general overview of how to perform file I/O in Golang:Import the necessary packages: Begin by importing the &#34;os&#34; package, which provides functions for file-re...