Go Language: User Input and the Power of Pointers

Go Language: User Input and the Power of Pointers

#90DaysOfDevOps

Day-12: Input from the user and use of pointers

In Golang, there are a few different ways to get input from the user. One way is to use the fmt package's Scanf() function. The Scanf() function takes a format string and a pointer to a variable. The format string tells the Scanf() function how to interpret the input. For example, the following code will get the user's name and store it in the name variable:

package main

import ( "fmt" )

func main() {
    var name string
    fmt.Scanf("%s", &name)
    fmt.Println("Enter your Name: ", name)
}

Using Pointers: Pointers in Go provide a way to manage memory and efficiently work with data. A pointer is a variable that holds the memory address of another variable. By using pointers, we can directly access and modify the value of the variable it points to, improving performance and memory efficiency.

To declare a pointer variable, we use the * symbol before the type. We can then assign the memory address of an existing variable to the pointer using the & operator. For example, namePtr = &name assigns the memory address of name to the namePtr pointer.

package main

import ( "fmt" )

func main() {
    var name string = "John Doe"
    namePtr := &name
    *namePtr = "Jane Doe"
    fmt.Println(name) // Jane Doe
}

By mastering these concepts, you'll be equipped to write more robust and efficient Go code. Remember to practice and experiment with user input and pointers in your projects to solidify your understanding. Happy coding with Go!

Did you find this article valuable?

Support Jatin Chourasia by becoming a sponsor. Any amount is appreciated!