github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume1/section2/funwithfuncs/funwithfuncs.go (about) 1 // Various examples of functions in Go. 2 package main 3 4 import "fmt" 5 6 // An example of a function that takes one input parameter, but does not return 7 // anything back. Thus, it is considered a void function. 8 9 var y = 4 10 11 func oddOrEven(x int) { 12 13 // Functions have a local scope. The variable x is only accessible within this function. 14 // For that reason we can consider x to be a local variable of the function. 15 if x%2 == 0 { 16 fmt.Println("The number,", x, ",is even.") 17 } else { 18 fmt.Println("The number,", x, ",is odd.") 19 } 20 21 // The variable y is visible inside this function, because it exists in the global 22 // scope. Therefore, y is a global variable. 23 if y%2 == 0 { 24 fmt.Println("The number,", y, ",is even.") 25 } else { 26 fmt.Println("The number,", y, ",is odd.") 27 } 28 29 } 30 31 // An example of a function that takes 2 input parameters and returns an output 32 // of type int 33 func sumTwoNumbers(x int, y int) int { 34 35 return x + y 36 } 37 38 // An example of a function returning multiple, named output parameters 39 func sumAndDiffOperationsOnTwoNumbers(x, y int) (sum int, difference int) { 40 return x + y, x - y 41 } 42 43 // An example of a variadic function, where we can supply a varying number of 44 // inputs of the same type 45 func multiSum(args ...int) int { 46 sum := 0 47 for i := 0; i < len(args); i++ { 48 sum += args[i] 49 } 50 51 return sum 52 } 53 54 // main() is a niladic function because it doesn't accept any arguments 55 func main() { 56 var numberToCheck = 7 57 oddOrEven(numberToCheck) 58 59 fmt.Println("The sum of 100 and 8: ", sumTwoNumbers(100, 8)) 60 61 sum, difference := sumAndDiffOperationsOnTwoNumbers(100, 8) 62 fmt.Printf("Input: 100 and 8, The Sum: %d Difference: %+v\n", sum, difference) 63 64 fmt.Println("Multi Sum result: ", multiSum(0, 5, 76, 2, 3, 4, 8, 1, 9)) 65 66 // Example of an anonymous function 67 func() { 68 fmt.Println("Hi I'm an anonymous function. They call me that, because I don't have a name!") 69 }() 70 71 }