Skip to main content

Command Palette

Search for a command to run...

Part 2: Write a program to take user input

Variables, DataTypes and stdin

Updated
2 min readView as Markdown
Part 2: Write a program to take user input
A

I am a full-stack developer at BigBinary.

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.Scanln(&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: https://tour.golang.org/basics/11.

fmt.Scanln(&first_name)

  • 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.

Learn Go by writing programs

Part 2 of 2

In this series, we will be diving into Golang by building small programs.Towards the end of the series, we will be able to write some micro-services in Golang.

Start from the beginning

Part 1: Hello Gopher

Learn about package, main, fmt.Println !