Level: BeginnerGo Programs

Go Print Programs with Output: Hello World, Println, Printf

Updated 17 min read
Go Print Programs featured image: terminal showing Hello World and Printf output

Go print programs are the first real programs every learner writes, starting with the classic Hello World. In this post, you will write twelve small Go print programs that print text, numbers and tables, each with its exact output. After that, you will practice the print questions that interviewers love, because they test how well you know Go’s rules.

This post starts Level 2 of our Go programs series. Before you begin, make sure you know how to run a Go program with go run .. You can also test every program here in an online Go compiler, since none of them read input. We tested all programs on Go 1.27.

What are Go Print Programs?

A print program sends text to the screen. In Go, you use the fmt package for this. Its name is short for “format”, and it gives you functions like Println, Print and Printf.

Think of fmt as a printer in an office. Println prints a page and moves to the next line. Print keeps writing on the same line. Printf lets you fill in a form, where you decide exactly where each value goes.

Why Practice Go Print Programs?

Printing looks simple, but it shows up in every program you will ever write. For example, you print results, debug values and error messages. Interviewers also ask “what does this print?” questions to test your attention to detail.

  • Debugging: printing a value with %v or %T is the quickest way to see what a variable holds.
  • Reports: with width and padding, you can print neat tables and receipts.
  • Interviews: many output questions depend on how Println adds spaces and new lines.

How Go Print Programs Work

Every print call follows the same path. Your program passes values to an fmt function. Then the function turns each value into text and writes it to standard output, which is usually your terminal.

Go print programs diagram showing values passing through fmt functions to the terminal
Your values go into an fmt function, which formats them as text and writes them to standard output.

The table below compares the three main print functions.

FunctionAdds spaces between valuesAdds new line at endUses format verbs
fmt.PrintOnly between two non-stringsNoNo
fmt.PrintlnAlwaysYesNo
fmt.PrintfNoNo, add \n yourselfYes
fmt.SprintfNoNoYes, returns a string
Go print programs comparison of Print, Println and Printf
Print keeps text on one line, Println adds spaces and a new line, and Printf follows your format string.

Basic Go Print Programs

Let’s start with the simplest Go print programs. Each one is complete, so you can copy it into main.go and run it.

Program 1: Hello World in Go

This is the first program in almost every language. It prints one line and ends.

package main // package main makes this a runnable program

import "fmt" // fmt is the standard package for printing

// main is where the program starts
func main() {
    fmt.Println("Hello, World!") // print the text, then move to a new line
}
Hello, World!

package main makes this a runnable program, and func main() is where it starts. fmt.Println prints the text and adds a new line at the end.

Program 2: Print Many Values with Println

Println can take any number of values of any type. It puts one space between them.

package main

import "fmt"

// main prints a name, an age and a height in one line
func main() {
    // := creates a new variable and Go picks its type from the value
    name := "Asha"  // a string (text)
    age := 25       // an int (whole number)
    height := 5.4   // a float64 (decimal number)

    fmt.Println("Name:", name, "Age:", age, "Height:", height)
}
Name: Asha Age: 25 Height: 5.4

Here, Go printed a string, an int and a float64 in one call. So you do not need to convert numbers to text first.

Program 3: Print vs Println on the Same Line

Print does not add a new line. So the next print continues on the same line.

package main

import "fmt"

// main builds one line with three Print calls, then prints a second line
func main() {
    fmt.Print("Go ")  // no new line after this
    fmt.Print("is ")
    fmt.Print("fun")
    fmt.Println() // an empty Println just ends the line

    fmt.Println("Next", "line")
}
Go is fun
Next line

The empty fmt.Println() call just prints a new line. We added the spaces ourselves inside the strings, because Print only adds spaces between two values when neither one is a string.

Program 4: Simple Maths in Go Print Programs

Go print programs can show the answer to a sum right away. Go works out the maths first, and then it prints the result.

package main

import "fmt"

// main prints the results of four simple sums
func main() {
    apples := 12
    oranges := 8

    fmt.Println("Apples + oranges =", apples+oranges)
    fmt.Println("Apples - oranges =", apples-oranges)
    fmt.Println("Apples x oranges =", apples*oranges)
    fmt.Println("Apples / 4 =", apples/4) // / divides whole numbers
}
Apples + oranges = 20
Apples - oranges = 4
Apples x oranges = 96
Apples / 4 = 3

First, the program stores two numbers in variables. Then each Println line does one sum and prints the text with the answer. The text inside quotes is printed as it is, so “x” is just a letter there.

Formatted Go Print Programs with Printf

Formatted Go print programs use Printf with format verbs. A verb is a placeholder that starts with %, such as %d for a whole number. Go swaps each verb for the matching value in order.

Program 5: Your First Printf Line

Let’s start with just two verbs. %s stands for a string, and %d stands for a whole number.

package main

import "fmt"

// main fills a sentence with a name and an age
func main() {
    name := "Ravi"
    age := 30

    // %s is replaced by name, %d by age, and \n starts a new line
    fmt.Printf("%s is %d years old.\n", name, age)
}
Ravi is 30 years old.

Go reads the format string from left to right. It puts name where %s is and age where %d is. The \n at the end moves the cursor to the next line.

Program 6: Common Format Verbs

This program prints the same kinds of values with the most useful verbs.

package main

import "fmt"

// main shows the most useful Printf verbs, one per line
func main() {
    city := "Pune"
    marks := 87
    price := 249.5
    passed := true

    fmt.Printf("City: %s\n", city)            // %s: plain text
    fmt.Printf("Quoted: %q\n", city)          // %q: text inside quotes
    fmt.Printf("Marks: %d\n", marks)          // %d: whole number
    fmt.Printf("Price: %.2f\n", price)        // %.2f: decimal with 2 places
    fmt.Printf("Passed: %t\n", passed)        // %t: true or false
    fmt.Printf("Type of price: %T\n", price)  // %T: the type name
    fmt.Printf("Any value: %v\n", marks)      // %v: any value, default form
    fmt.Printf("Discount: 10%%\n")            // %%: a real percent sign
}
City: Pune
Quoted: "Pune"
Marks: 87
Price: 249.50
Passed: true
Type of price: float64
Any value: 87
Discount: 10%

Notice the \n at the end of each format string. Printf never adds a new line by itself. Also, %% prints a real percent sign.

Here is a quick reference of the verbs you will use most.

VerbPrintsExample output
%vAny value in default format87
%+vStruct with field names{Name:Ravi Age:30}
%#vGo syntax formmain.User{Name:”Ravi”}
%TThe typefloat64
%dWhole number87
%sStringPune
%qQuoted string“Pune”
%f / %.2fDecimal number249.50
%tBooleantrue
%xHexadecimalff
%cCharacter from a runeA
%%A percent sign%

Program 7: Print a Struct Three Ways

Structs hold related fields together. The %v, %+v and %#v verbs show them with more detail each time.

package main

import "fmt"

// User holds a person's name and age together
type User struct {
    Name string
    Age  int
}

// main prints one User with three different verbs
func main() {
    user := User{Name: "Ravi", Age: 30} // make a User value

    fmt.Printf("%v\n", user)  // values only
    fmt.Printf("%+v\n", user) // field names and values
    fmt.Printf("%#v\n", user) // the value written as Go code
}
{Ravi 30}
{Name:Ravi Age:30}
main.User{Name:"Ravi", Age:30}

Use %+v while debugging, because it shows which value belongs to which field. We cover structs fully later in this series.

Program 8: Width and Padding

You can set a width between % and the verb. A minus sign aligns text to the left, and a zero pads numbers with zeros.

package main

import "fmt"

// main prints values inside [ ] so you can see the padding spaces
func main() {
    fmt.Printf("[%5d]\n", 42)       // width 5, number on the right
    fmt.Printf("[%-5d]\n", 42)      // width 5, number on the left
    fmt.Printf("[%05d]\n", 42)      // width 5, filled with zeros
    fmt.Printf("[%8.2f]\n", 3.14159) // width 8, 2 decimal places
    fmt.Printf("[%-8s]\n", "Go")    // width 8, text on the left
    fmt.Printf("[%8s]\n", "Go")     // width 8, text on the right
}
[   42]
[42   ]
[00042]
[    3.14]
[Go      ]
[      Go]

The square brackets show where the spaces go. For example, %05d turns 42 into 00042, which is handy for order numbers.

Real-World Go Print Programs

Now let’s use these tools in Go print programs that do something useful.

Program 9: Print a Shop Receipt Table

This program prints a neat receipt with aligned columns. It uses a slice of structs and a loop, which we explain fully in later posts.

package main

import "fmt"

// Item is one line on the receipt
type Item struct {
    Name     string
    Quantity int
    Price    float64
}

// main prints a receipt with aligned columns and a total
func main() {
    // a slice is a list; this one holds three Item values
    items := []Item{
        {"Notebook", 2, 45.00},
        {"Pen", 5, 10.50},
        {"Bag", 1, 799.99},
    }

    // Step 1: print the header row
    fmt.Printf("%-10s %4s %9s\n", "Item", "Qty", "Amount")

    // Step 2: print each item and add its amount to the total
    total := 0.0
    for _, item := range items { // range gives each item in turn; _ skips the position
        amount := float64(item.Quantity) * item.Price // turn the int into a float64 before multiplying
        total += amount
        fmt.Printf("%-10s %4d %9.2f\n", item.Name, item.Quantity, amount)
    }

    // Step 3: print the total row
    fmt.Printf("%-10s %4s %9.2f\n", "Total", "", total)
}
Item        Qty    Amount
Notebook      2     90.00
Pen           5     52.50
Bag           1    799.99
Total              942.49

%-10s keeps names on the left in a 10-character column, while %9.2f lines up the amounts on the right. As a result, the decimal points sit in one straight line.

Program 10: Build a String with Sprintf

Sprintf works like Printf, but it returns the text instead of printing it. This is useful for messages, file names and logs.

package main

import "fmt"

// main builds a message with Sprintf, then prints it and its length
func main() {
    orderID := 7
    customer := "Meera"

    // %03d prints the number with at least 3 digits, adding zeros in front
    message := fmt.Sprintf("Order #%03d is ready for %s", orderID, customer)

    fmt.Println(message)
    fmt.Println("Length:", len(message)) // len counts the characters (bytes)
}
Order #007 is ready for Meera
Length: 29

Because message is a normal string, you can store it, send it or print it later.

Program 11: Escape Sequences and Raw Strings

Escape sequences are special pairs that start with a backslash. A raw string uses backticks, so Go prints it exactly as written.

package main

import "fmt"

// main prints special characters, then a raw string
func main() {
    fmt.Println("Name:\tAsha")         // \t is a tab
    fmt.Println("She said \"Hi\"")     // \" prints a double quote
    fmt.Println("Path: C:\\Go\\bin")   // \\ prints one backslash
    fmt.Println(`Raw: C:\Go\bin\n stays as typed`) // backticks: nothing is special
}
Name:	Asha
She said "Hi"
Path: C:\Go\bin
Raw: C:\Go\bin\n stays as typed

\t adds a tab, \" prints a quote and \\ prints one backslash. Inside backticks, none of these are special.

Program 12: Print Unicode and Characters

Go strings are UTF-8, so you can print text in Hindi, Marathi or any other language. A rune is one Unicode character.

package main

import "fmt"

// main prints a rune three ways, then some Hindi text
func main() {
    letter := 'A' // single quotes make a rune, which is a character code

    fmt.Println(letter)                              // prints the number 65
    fmt.Printf("%c %d %U\n", letter, letter, letter) // %c letter, %d number, %U Unicode code
    fmt.Println("नमस्ते", "Go")
}
65
A 65 U+0041
नमस्ते Go

Println prints a rune as its number, 65. To see the letter, use %c. This surprises many beginners, so it is a common interview question.

Common Mistakes in Go Print Programs

These are the errors we see most often in beginner code.

  • Forgetting \n in Printf: all output lands on one line. Add \n at the end of the format string.
  • Wrong verb for the type: %d with a string prints %!d(string=...). Run go vet to catch it early.
  • Too few values: a missing value prints %!d(MISSING), so count your verbs.
  • Printing a rune with Println: you get a number. Use %c or string(r) for the character.
  • Unused import: importing fmt and not using it is a compile error in Go.

Best Practices for Go Print Programs

Follow these habits to keep your Go print programs clean and easy to read.

  • Use Println for quick output and Printf when you need control over layout.
  • Pick %+v for debugging structs, so field names are visible.
  • Use Sprintf to build strings instead of joining many pieces with +.
  • Send errors to standard error with fmt.Fprintln(os.Stderr, ...), so they do not mix with normal output.
  • Run go vet, because it checks every Printf call for wrong verbs.

Go Print Programs Interview Questions and Answers

Interviewers often use Go print programs to test your knowledge of output rules. Each program is complete, and we show the real output from Go 1.27.

Println Questions in Go Print Programs

Q1. What is the difference between Print, Println and Printf?

Print writes values with no new line. Println adds spaces between values and a new line at the end. Printf follows a format string with verbs and adds nothing extra.

Q2. What does this program print?

package main

import "fmt"

// main mixes strings and numbers in one Print call
func main() {
    fmt.Print("a", "b", 1, 2, "c")
    fmt.Println() // end the line
}
ab1 2c

Print adds a space only between two values when neither is a string. So “a” and “b” join, 1 and 2 get a space, and “c” joins the 2.

Q3. What does this program print?

package main

import "fmt"

// main prints the same values with Println
func main() {
    fmt.Println("a", "b", 1, 2, "c")
}
a b 1 2 c

Println always adds a space between every value. That is the key difference from Print.

Q4. What is the difference between println and fmt.Println?

println is a built-in function meant for debugging the Go runtime. It writes to standard error, and its format may change. In real code, always use fmt.Println.

Q5. What does fmt.Println return?

It returns two values: the number of bytes written and an error. Most code ignores them, but you can check them.

package main

import "fmt"

// main prints "Hello" and then the two values Println returned
func main() {
    // bytesWritten is how many bytes were printed
    // err is the error value; nil means no error
    bytesWritten, err := fmt.Println("Hello")
    fmt.Println(bytesWritten, err)
}
Hello
6 <nil>

“Hello” is 5 bytes, and the new line adds 1 more, so bytesWritten is 6. The error is nil because the write worked.

Printf and Format Verb Questions

Q6. What does this program print?

package main

import "fmt"

// main makes two common Printf mistakes on purpose
func main() {
    fmt.Printf("%d\n", "ten")  // wrong type: %d needs a number
    fmt.Printf("%d %d\n", 5)   // missing value: two verbs, one value
}
%!d(string=ten)
5 %!d(MISSING)

Go does not crash on a bad verb. Instead, it prints a clear marker that shows the problem. go vet reports both lines before you even run the code.

Q7. How do you print the type of a variable?

Use the %T verb. For example, fmt.Printf("%T", 3.5) prints float64.

Q8. What does this program print?

package main

import "fmt"

// main shares 10 sweets among 3 children, first as whole numbers, then as decimals
func main() {
    sweets := 10
    children := 3

    // int / int gives an int, so the decimal part is dropped
    fmt.Println(sweets / children)

    // float64(...) turns each int into a decimal number before dividing
    fmt.Printf("%.2f\n", float64(sweets)/float64(children))
}
3
3.33

Dividing two ints gives an int, so the decimal part is dropped. To get 3.33, convert to float64 first and use %.2f.

Q9. How do you print a percent sign with Printf?

Write %%. A single % starts a verb, so Go needs two to print one.

Q10. What does this program print?

package main

import "fmt"

// main builds a string with Sprint, then prints it and its length
func main() {
    text := fmt.Sprint("Go", 1, 2, "!") // Sprint returns the text instead of printing it
    fmt.Println(text)
    fmt.Println(len(text))
}
Go1 2!
6

Sprint follows the same spacing rule as Print, but returns a string. The result “Go1 2!” has 6 characters.

Q11. What is the difference between %v, %+v and %#v?

%v prints the default form. %+v adds field names for structs. %#v prints the value as Go code, including the type name.

Runes, Strings and Special Values

Q12. What does this program print?

package main

import "fmt"

// main prints a rune as a number and then as a letter
func main() {
    letter := 'G'
    fmt.Println(letter)         // the character code
    fmt.Println(string(letter)) // string(...) turns the code into text
}
71
G

A rune is an alias for int32, so Println shows its number. Converting with string(letter) gives the letter.

Q13. What does this program print?

package main

import "fmt"

// main prints three variables that were never given a value
func main() {
    var pointer *int         // *int is a pointer to an int; its zero value is nil
    var numbers []int        // a slice of ints with nothing in it
    var ages map[string]int  // a map from names to ages, also empty
    fmt.Println(pointer, numbers, ages)
}
<nil> [] map[]

All three are zero values. A nil pointer prints <nil>, while a nil slice and a nil map print as empty.

Q14. What does this program print?

package main

import "fmt"

// main compares the byte length of English and Hindi text
func main() {
    // len counts bytes, not letters
    fmt.Println(len("Go"), len("हिं"))
}
2 9

len counts bytes, not characters. Each Hindi character here takes 3 bytes in UTF-8, so the result is 9.

Q15. What does this program print?

package main

import "fmt"

// main prints numbers in base 16, base 8 and base 2
func main() {
    // %x small hex, %X capital hex, %o octal, %b binary
    fmt.Printf("%x %X %o %b\n", 255, 255, 8, 5)
}
ff FF 10 101

%x and %X print hexadecimal in lower and upper case. %o prints octal, and %b prints binary.

Q16. What does this program print?

package main

import "fmt"

// main prints three decimals with different widths and padding
func main() {
    // %6.2f: width 6, 2 places | %-6.1f: left aligned | %06.2f: zero padded
    fmt.Printf("%6.2f|%-6.1f|%06.2f\n", 3.14159, 2.5, 3.14159)
}
  3.14|2.5   |003.14

The number before the dot is the full width, and the number after it is the decimal places. A minus sign aligns left, and a zero pads with zeros.

Output Destination Questions

Q17. How do you print an error message to standard error?

Use fmt.Fprintln(os.Stderr, "message"). The first argument is any io.Writer, so the same function can also write to files or network connections.

Q18. Can you print without the fmt package?

Yes. You can use os.Stdout.WriteString("hi\n"), the log package, or the built-in println. However, fmt is the normal choice for program output.

Q19. What does this program print?

package main

import "fmt"

// main shows that + adds numbers but joins strings
func main() {
    first := 5
    second := 7
    fmt.Println("Sum:", first+second, "Product:", first*second)
    fmt.Println("Text: " + "5" + "7") // "5" and "7" are strings, so + joins them
}
Sum: 12 Product: 35
Text: 57

With numbers, + adds them. With strings, + joins them. So “5” + “7” gives “57”, not 12.

Q20. What does this program print?

package main

import "fmt"

// main prints a bool and the same slice with two verbs
func main() {
    letters := []string{"a", "b"} // a slice of two strings
    fmt.Printf("%t %v %q\n", 1 > 2, letters, letters)
}
false [a b] ["a" "b"]

%t prints a boolean, and %v prints a slice inside square brackets. %q puts quotes around each string in the slice.

Practice Task

This task combines all the Go print programs above. Write a program that prints a marks card for three subjects, with the subject name on the left, marks on the right, and the average with one decimal place. Hint: use %-12s for names and %6.1f for the average.

Official Resources

Quick Recap

  • Go print programs use the fmt package: Print, Println, Printf and Sprintf.
  • Println adds spaces and a new line, but Printf adds nothing unless you write \n.
  • Format verbs like %d, %s, %.2f, %T and %+v control how values look.
  • Width and padding, such as %-10s and %05d, help you print neat tables.
  • A rune prints as a number with Println, so use %c to see the character.

What’s Next?

Next, your programs start talking to the user. Read Go user input programs with fmt.Scan and bufio. To revise the basics of values first, see Go variables, constants and data types.