Today I am starting the 30 days of code challenge on Hackerrank. You will be able to see my progress at my profile. The language I chose is Go. I do not have experience in Go and I am pretty excited. I think the challenge is basic, but it will probably be fun, so bear with me. Later on I may take better challenges, when I get more experience with Hackerrank.

Incredibly, this gave me more trouble than I expected. First of all I had to install go using homebrew:

$ brew install go

And then I had to write a program for the first day. The goal was to read a variable from standard input and then print it to the standard output. In C, I would just use scanf but the solution in Go that worked first for me was using a bufio reader:

package main

import (
 "fmt"
 "bufio"
 "os"
)

func main() {
  // create a reader that can be called
  // multiple times
  reader := bufio.NewReader(os.Stdin)
  // reads a variable from stdin
  text, _ := reader.ReadString('\n')
  //prints to stdout
  fmt.Printf("Hello, World.\n")
  fmt.Printf("%s\n", text)
}

I had a problem using fmt.Scanln to read a single input line. Why? Well, I tried this:

package main

import "fmt"

func main() {
 var input string
 fmt.Scanln(&input)
 //prints to stdout
 fmt.Printf("Hello, World.\n")
 fmt.Printf("%s\n", input)
}

For some reason, input here was storing only the first word and everything else was not stored… what gave me troubles with the tests. Then I read the Golang documentation which says Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF and I didn’t exactly understand what it means to be similar to Scan but when I looked it up it said Scan scans text read from standard input, storing successive space-separated values into successive arguments. Well, this made clear that the Scanln was not what I actually needed. It is also possible to use Scanf:

package main

import "fmt"

func main() {
 var input string
 fmt.Scanf("%q", &input)
 //prints to stdout
 fmt.Printf("Hello, World.\n")
 fmt.Printf("%s\n", input)
}

Then the input to the program and output would be

$ ./day_01
Tudo bem?
Hello, World.
Tudo bem?

That’s all for today, thanks for reading! Do not hesitate to comment!