strings input output



This snippet prints str1 to the screen, waits for your input, then prints out that input...

package main
import "fmt"

func main() {
    var myname string
    str1 := "What is your name?"
    fmt.Println(str1)
    fmt.Scanf("%s", &myname)
    fmt.Println("Hello", myname)
}

...and a few more:
package main
import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("What is your favorite color?")
    var favoriteColor string
    fmt.Scanf("%s", &favoriteColor)
    fmt.Println("Fave color is", favoriteColor)
    fmt.Println("What is your favorite food?")
    var myfood string
    fmt.Scanf("%s", &myfood)
    fmt.Printf("I like %s too!\n", myfood)
    fmt.Printf("Wait two seconds please...\n")
    time.Sleep(2000 * time.Millisecond)
    fmt.Printf("Your favorite color is %s, and the food you like best is %q\n", favoriteColor, myfood)
}

5 comments:

  1. Could you please explain, why we should use format argument in Scanf function?
    If we already have declared myname variable as string, why it's not enough to do something like this: fmt.Scanf(&myname)?

    ReplyDelete
    Replies
    1. That is because in the definition of Scanf the parameter is an empty interface, which can take any type of object.

      Delete
    2. That is because in the definition of Scanf the parameter is an empty interface, which can take any type of object.

      Delete
    3. And that's why we should send the type of the argument in the format string, right?

      Delete