Reusing code with procedures
Procedures are are the simplest black boxes in code. To use a procedure, you just need to know what it does. You don’t need to see what happens inside it until it does something unexpected or wrong. Let’s write a function that doubles a number.
flowchart LR;
input --> newLines["`**Procedure**
Line 1
Line 2
Line 3
...`"] --> output;
/// Doubles a number and returns
double :: proc(n: int) -> int {
return 2 * n
}
Comments
Comments are ignored by Odin. They are only for humans to make the code easier to understand.
- Use lines that start with
///above procedures to explain them. These are called doc strings. - Use
//for comments - Put multiline comments between
/* ... */
Input and output types
double :: proc(n: int) -> int
proc(n: int) indicates that that it takes an int (integer) called n and -> int means the proc returns an int. The int type is inbuilt. It can store both negative and positive numbers.
Return statement
return 2*n means the procedure exits with a value of 2 * n for any n passed into it.
Let’s use this proc to print double of 3 and 5.
main :: proc() {
fmt.println(double(3)) // prints 6
fmt.println(double(5)) // prints 10
}
We will look at procs and types (like int) in detail in the coming chapters.