It is possible to use the Caesar cipher to obscure text in Go programs. By shifting letters, we can encode a message. This deters casual snooping.
In Go we can implement the Caesar cipher with the strings.Map
method. We avoid complex for
-loops and bug-prone code this way.
Let us begin. We introduce the caesar()
method. This receives a rune
and returns a modified rune
. It shifts characters, and then shifts characters to a valid range.
main()
method control flow begins. To call caesar()
within the strings.Map
method, we use funcs.func
we define calls the caesar()
method with a special shift argument. This shifts characters by that number of places.strings.Map
method can only call a method that receives and returns a rune
. The shift argument is specified in a wrapper func
.package main import ( "fmt" "strings" ) func caesar(r rune, shift int) rune { // Shift character by specified number of places. // ... If beyond range, shift backward or forward. s := int(r) + shift if s > 'z' { return rune(s - 26) } else if s < 'a' { return rune(s + 26) } return rune(s) } func main() { value := "test" fmt.Println(value) // Test the caesar method in a func argument to strings.Map. value2 := strings.Map(func(r rune) rune { return caesar(r, 18) }, value) value3 := strings.Map(func(r rune) rune { return caesar(r, -18) }, value2) fmt.Println(value2, value3) value4 := strings.Map(func(r rune) rune { return caesar(r, 1) }, value) value5 := strings.Map(func(r rune) rune { return caesar(r, -1) }, value4) fmt.Println(value4, value5) value = "exxegoexsrgi" result := strings.Map(func(r rune) rune { return caesar(r, -4) }, value) fmt.Println(value, result) }test lwkl test uftu test exxegoexsrgi attackatonce
The strings.Map
is a good way to translate characters in strings. But its first argument is a func
that only receives a rune
(and no shift value).
strings.Map
in this way is reliable.This method will not work correctly on uppercase letters. To add support for uppercase letters, please try adding another pair of if-else
statements.
The Caesar cipher is similar to the ROT13 cipher, but it accommodates any shift value. It is not useful for battles anymore. But it can help us learn more about how to use Go.