This is day 4 out of 100 days of code.
Two code snippets today. First is very simple go channel.
It get current system time and post it to a channel then on other end message retrieved out of the channel and printed.
package main import ( "fmt" "time" ) func main() { messages := make(chan string) go func() { for { messages <- fmt.Sprintf("Time now %s\n", time.Now()) time.Sleep(100 * time.Millisecond) } }() for { msg := <-messages fmt.Println(msg) } }
Second code snippet is a program which check two strings for anagram. When one string is equal reverse of other it is anagram.
package main import ( "flag" "fmt" ) func main() { str1 := flag.String("first", "", "first string for anagram check") str2 := flag.String("second", "", "second string for anagram check") flag.Parse() checkForAnagrams(*str1, *str2) } func checkForAnagrams(str1, str2 string) { if len(str1) != len(str2) { fmt.Printf("%s and %s are not anagrams", str1, str2) return } for i := 0; i < len(str1); i++ { if str1[i] != str2[len(str2)-i-1] { fmt.Printf("%s and %s are not anagrams", str1, str2) return } } fmt.Printf("%s and %s are anagrams", str1, str2) }