Skip to content

Latest commit

 

History

History
173 lines (133 loc) · 2.45 KB

Module2Week1.org

File metadata and controls

173 lines (133 loc) · 2.45 KB

Module2

Functions - Week 1

A set of instructions with a name

Example

Directly

package main

import ("fmt")

func main () {
	fmt.Printf("Hello, world.")
}

With a helper function

package main

import ("fmt")

func PrintHello () {
	fmt.Println("Hello, world!")
}

func main () {
	PrintHello()
}

Example

See the following pseudo-code.

func FindPupil () {
	GrabImage ()
	FilterImage ()
	FindEllipses ()
}

Parameters and Arguments

  • x and y are parameters;
  • 2 and 3 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)
}

Return values

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.

Call by Reference

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)
}