Monday, September 7, 2020

Golang: basic function

 two separate function calls from main function:

package main
import "fmt"
var lightSwitchIsOn bool = false
func main(){
 printLightSwitchState()
 toggleLightSwitch()
 printLightSwitchState()
 toggleLightSwitch()
 printLightSwitchState()
}
func printLightSwitchState(){
 fmt.Println("The light switch is off:",lightSwitchIsOn)
}
func toggleLightSwitch(){
 lightSwitchIsOn = !lightSwitchIsOn
}

two int parameters and one int output
func sumTwoNumbers(x int,y int) int{
 return x+y
}

two return values
func sumAndDiffTwoNumbers(x, y int) (sum int,difference int){
 return x+y,x-y
}

Can call it using:
a,b:=sumAndDiffTwoNumbers(25,23)

variable number of inputs--variadic function,main is niladic as no arguments
func multisum(args ...int)int{
 sum :=0
 for i:=0; i<len(args);i++{
  sum+=args[i]
 }
 return sum
}

No comments:

Post a Comment