Part 2: Write a program to take user input

Part 2: Write a program to take user input

Variables, DataTypes and stdin

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In this part, first, we are going to write a program that takes user input and prints it.

package main

import "fmt"

func main() {
  var first_name string
  fmt.Println("Please enter your first name:")
  fmt.Printf("Your name is %s", first_name)
  // or
  // fmt.Println("Your name is ", first_name)

var first_name string

  • var keyword is used to declare a variable. It is followed by the name of the variable, which is first_name in this case and then we have to specify the data type, that is string here.
  • Variables can also be declared with initialization.

    var first_name string = "akhil"
    // multiple same data-type variables can be declared as follows:
    var maths_score, physics_score
    // they can be initialized too:
    var maths_score, physics_score int = 89, 95
  • Variables can also be declared without var and data-type when declared inside a function using := construct.
    first_name := "akhil"
    bats_count := 3
  • All the different data types available in Go can be found here: tour.golang.org/basics/11.


  • Scanln present in fmt is used to read from standard input. It stops reading whenever it finds a newline. Scanln takes the reference to the variable where it needs to store the value it reads. We will expand more on &variable syntax when we reach pointers. For now, just note that we need to provide &variable to Scanln in order to store the input in the variable.

fmt.Printf("Your name is %s", first_name)

  • Printf is used to print to standard output according to the format specifier used. Think of format specifier as a bucket that can only hold a specific type of data. So for holding string data, we have used %s. Read more about fmt.Printf here...

In the next part, we will see conditionals. Thanks for reading this.

Interested in reading more such articles from Akhil Gautam?

Support the author by donating an amount of your choice.

Recent sponsors
Share this
Proudly part of