Created
October 1, 2015 09:35
-
-
Save emmaly/7c85c14f29fba7273b39 to your computer and use it in GitHub Desktop.
Go Decorator Example
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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
// An Adder adds two ints and returns an int | |
type Adder func(a int, b int) int | |
// Add boringly adds two integers and returns an int | |
func Add(a int, b int) int { | |
return a + b | |
} | |
// GoofyAdd goofily adds two integers and returns an int | |
func GoofyAdd(adder Adder) Adder { | |
return func(a int, b int) int { | |
a += rand.Intn(100) | |
return adder(a, b) | |
} | |
} | |
// LossyAdd lossily adds two integers and returns an int | |
func LossyAdd(adder Adder) Adder { | |
return func(a int, b int) int { | |
b /= 2 | |
return adder(a, b) | |
} | |
} | |
// GenerousAdd generously adds two integers and returns an int | |
func GenerousAdd(adder Adder) Adder { | |
return func(a int, b int) int { | |
a *= 10 | |
b += 1000 | |
return adder(a, b) | |
} | |
} | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
adder := Add | |
adder = GoofyAdd(Add) | |
adder = LossyAdd(adder) | |
adder = GenerousAdd(adder) | |
adder = GenerousAdd(LossyAdd(GoofyAdd(LossyAdd(GenerousAdd(adder))))) | |
fmt.Println(adder(123, 99)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment