Last active
October 24, 2017 15:34
-
-
Save masutaka/47edd1540fbafc1037057e021f246bc2 to your computer and use it in GitHub Desktop.
go memorize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Memorize using closure | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func urlFunc() func() string { | |
var url string | |
return func() string { | |
if url == "" { | |
time.Sleep(3 * time.Second) | |
url = "https://masutaka.net" | |
} | |
return url | |
} | |
} | |
func main() { | |
url := urlFunc() | |
fmt.Println("part1") | |
fmt.Println(time.Now()) | |
fmt.Println(url()) | |
fmt.Println(time.Now()) | |
fmt.Println(url()) | |
fmt.Println(time.Now()) | |
fmt.Println(url()) | |
fmt.Println() | |
url2 := urlFunc() | |
fmt.Println("part2") | |
fmt.Println(time.Now()) | |
fmt.Println(url2()) | |
fmt.Println(time.Now()) | |
fmt.Println(url2()) | |
fmt.Println(time.Now()) | |
fmt.Println(url2()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Memorize using struct | |
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
// Masutaka struct | |
type Masutaka struct { | |
url string | |
} | |
func (m *Masutaka) getURL() string { | |
if m.url == "" { | |
time.Sleep(3 * time.Second) | |
m.url = "https://masutaka.net" | |
} | |
return m.url | |
} | |
func main() { | |
m := &Masutaka{} | |
fmt.Println("part1") | |
fmt.Println(time.Now()) | |
fmt.Println(m.getURL()) | |
fmt.Println(time.Now()) | |
fmt.Println(m.getURL()) | |
fmt.Println(time.Now()) | |
fmt.Println(m.getURL()) | |
fmt.Println() | |
fmt.Println("part1b") | |
fmt.Println(time.Now()) | |
fmt.Println(m.url) | |
fmt.Println(time.Now()) | |
fmt.Println(m.url) | |
fmt.Println(time.Now()) | |
fmt.Println(m.url) | |
fmt.Println() | |
m2 := &Masutaka{} | |
fmt.Println("part2") | |
fmt.Println(time.Now()) | |
fmt.Println(m2.getURL()) | |
fmt.Println(time.Now()) | |
fmt.Println(m2.getURL()) | |
fmt.Println(time.Now()) | |
fmt.Println(m2.getURL()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment