×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to print Hello World

Last Updated : April 20, 2025

In this program, we will create a string variable, which is initialized with a "Hello World" message, and then we will print the message on the console screen.

Hello World Program in Golang

The source code to print "Hello World" is given below. The given program is compiled and executed successfully.

package main
import "fmt"

func main() {
    var var1 string

    var1 = "Hello World"
    fmt.Println(var1)
}

When executed, this program outputs:

Hello World

Print Any String (or, Hello World) Using fmt.Println()

The fmt.Println() function automatically adds a newline after the output, which is convenient for printing simple messages without formatting.

Example

package main
import "fmt"

func main() {
    var message string
    message = "Hello World"
    fmt.Println(message)
}

When executed, this program outputs:

Hello World

Explanation: This approach uses fmt.Println() to print the string "Hello World" and automatically inserts a newline after it. It's a straightforward and commonly used method in Go.

Print Hello World with fmt.Printf()

The fmt.Printf() function allows you to format the string, add variables, or adjust the output as needed.

Example

package main
import "fmt"

func main() {
    var message string
    message = "Hello World"
    fmt.Printf("The message is: %s\n", message)
}

When executed, this program outputs:

The message is: Hello World

Explanation: Here, the string "Hello World" is printed with a custom message using fmt.Printf(). This method allows more flexibility in formatting the output, such as adding additional text or variables to the print statement.

Print Hello World Using String Variables for Dynamic Output

In this approach, you can use variables to store string (Hello World) and print them dynamically. This method is useful when the value of the string is determined at runtime or fetched from other parts of the program.

Example

package main
import "fmt"

func main() {
    var message string
    message = "Hello, dynamic world!"
    fmt.Println(message)
}

When executed, this program outputs:

Hello, dynamic world!

Explanation: This approach demonstrates how to dynamically assign a string to a variable and print it. The value of the string can be changed based on the program's logic.

Golang Basic Programs »



Related Programs

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.