A set of instructions with a name
package main
import ("fmt")
func main () {
fmt.Printf("Hello, world.")
}
package main
import ("fmt")
func PrintHello () {
fmt.Println("Hello, world!")
}
func main () {
PrintHello()
}
See the following pseudo-code.
func FindPupil () {
GrabImage ()
FilterImage ()
FindEllipses ()
}
x
andy
are parameters;2
and3
are arguments.
parameters: variables in the design of the function. arguments: variables-value in the call of the function.
package main
import ("fmt")
func foo(x int, y int){
fmt.Println(x*y)
}
func main(){
foo(2,3)
}
package main
import ("fmt")
func foo(x, y int) int{
return x*y
}
func main(){
y := foo(3,4)
fmt.Println(y)
}
package main
import ("fmt")
func foo(x, y int) (int, int){
return x*y, 2*x*y
}
func main(){
y, y2 := foo(3,4)
fmt.Println(y,y2)
}
package main
import ("fmt")
func foo(x, y int) (int, int){
return x*y, 2*x*y
}
func main(){
x := 3
y := 4
w, z := foo(x,y)
fmt.Println("x:",x,"y:",y,"w:",w,"z:",z)
}
Note the value of x
and y
does not go through changes when we call
foo(x,y)
, because only the environmental variables - e.i., it’s copies - are
being used to perfom tasks.
To “burlate” environmental encapsulation for performance, we can use pointers.
package main
import ("fmt")
func foo(x *int, y *int){
*x = (*x)*(*y)
*y = 2*(*x)
}
func main(){
x:=3
y:=4
foo(&x,&y)
fmt.Println("x:",x,"y:",y)
}