This cipher obscures the characters in a string
. With ROT13, characters are rotated 13 places in the alphabet. Other characters are not changed.
In Go, a method in the strings package can be used to translate strings. This is the Map method. It receives a func
that receives a rune
, and returns a translated one.
First we define the rot13
method. This receives a rune
and returns a rune
. It contains the translation logic for the rotation of characters.
func
that translates a rune
.rot13
transformation. The input string
is obscured.package main import ( "fmt" "strings" ) func rot13(r rune) rune { if r >= 'a' && r <= 'z' { // Rotate lowercase letters 13 places. if r >= 'm' { return r - 13 } else { return r + 13 } } else if r >= 'A' && r <= 'Z' { // Rotate uppercase letters 13 places. if r >= 'M' { return r - 13 } else { return r + 13 } } // Do nothing. return r } func main() { input := "Do you have any cat pictures?" mapped := strings.Map(rot13, input) fmt.Println(input) fmt.Println(mapped) }Do you have any cat pictures? Qb lbh unir nal png cvpgherf?
In the Go strings package documentation, a ROT13 example is presented for the Map method. This uses more complex logic, with modulo division.
if-else
statements when possible—these are easier to reason about for new developers.For ROT13 methods, a translation method is usually the clearest approach. A new string
could be built up, in a loop over the characters, but this is less clear.
strings.Map
are ideal for transforming strings based on characters.ROT13 is not a secure cipher. It can easily be reversed. But it might help reduce casual snooping on a piece of text. And it helps us learn about string
transformation methods.