C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: In this method control flow begins. To call caesar() within the strings.Map method, we use funcs.
Func: Each func we define calls the caesar() method with a special shift argument. This shifts characters by that number of places.
Note: The strings.Map method can only call a method that receives and returns a rune. The shift argument is specified in a wrapper func.
Warning: A global variable could be used to control the shift number, but this is not accepted as good programming practice.
Golang program that implements caesar cipher
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)
}
Output
test
lwkl test
uftu test
exxegoexsrgi attackatonce
So: We can modify how a method is called by adding another "wrapper" method that specifies the shift in an internal method calls.
Note: In some ways, this implementation is less clear than a custom looping method, but using strings.Map in this way is reliable.