Header

Header

Sunday, May 12, 2019

Converting Python Caesar Cipher to Go Language Part 2

In this post we will continue converting the Caesar Cipher Python program to Go Language.

Let us take a look at the next function:

 def getMessage():  
   print('Enter your message:')  
   return input()  

In Python 3 you can use the input() function to capture console input to a variable.  The input() function has the following syntax:  input([prompt]).  Notice the prompt is an optional argument and is not used in the above code snippet.

The input() method reads a line from input (usually user), converts the line into a string by removing the trailing newline, and returns it.

Let us look at the converted Go code snippet:

 // get message to encrypt or decrypt  
 func getMessage() string {  
      reader := bufio.NewReader(os.Stdin)  
      // print the prompt  
      fmt.Println("Enter your message:")  
      // use new reader to grap message  
      input, _ := reader.ReadString('\n')  
      return input  
 }  

We cannot use any of the fmt.Scan() functions as white space, triggers the function to place the next alphanumeric characters into another variable.  In this situation we most likely want to capture a sentence of word separated by spaces.

In Go, one way to capture a sentence would be to use the reader.ReadString() function from the bufio package.  https://golang.org/pkg/bufio/

We again use the fmt.Println() function to prompt the user for input.

  input, _ := reader.ReadString('\n')   

Notice the input, _ :=  syntax.  The single "_" underscore character is a common operator in Go,  In this example the reader.ReadString() function can return more than one value.  In the case of many functions in Go they can return error information in additional to function results, in this case the entered string.

The single "_" underscore operator tells the Go compiler to ignore the second return value.

The := operator is a short cut declaration that lets the compiler determine the variable data type and assign the value to the variable.



No comments:

Post a Comment