Reusing Code with Procedures
Procedures (or functions in other languages) are like tiny machines. Like a cooker which takes rice, water and electricity as input and returns boiled rice after 30 minutes, a procedure (or proc in short) takes an input, transforms it in some way, and returns an output after sometime.
Procs are similar to mathematical functions.
flowchart LR;
input --> newLines["`**Procedure**
Line 1
Line 2
Line 3
...`"] --> output;
Let's write a proc that doubles a number.
/// Doubles a number and returns
double :: proc(n: int) -> int {
return 2 * n
}
Comments
Comments are ignored by the compiler. They are only for humans to make the code easier to understand.
- Use lines that start with
///above procedures to explain them. These are calleddoc strings. - Use
//for comments - Put multiline comments between
/* ... */
Input and Output Types
double :: proc(n: int) -> int
proc(n: int) indicates that it takes an int (integer) called n and -> int means the proc returns an int. The int type is inbuilt. It can represent both negative and positive numbers.
Return Is
The exit point of a function. return 2 * n means the procedure double ends and passes back \(2n\) to its caller - the main proc.
Let's use this proc to print double of 3 and 5. We can double negative numbers too.
main :: proc() {
fmt.println(double(3)) // prints 6
fmt.println(double(5)) // prints 10
fmt.println(double(-8)) // prints -16
}