# 2. Values and types ## Variables `var` makes a variable you can change. The type is worked out from the value. ```rex func main() { var score = 10 score = score + 5 score += 1 print(score) var name: string = "Rex" // you may write the type after a colon var ratio: float = 1 // a whole-number literal fits a float print(name, ratio) } ``` ```text 16 Rex 1.0 ``` `const` is a value that never changes. It must be known when the program is compiled (you can't call functions in it). ```rex const MAX = 100 const GREETING = "hi" func main() { print(MAX * 2, GREETING) } ``` ```text 200 hi ``` > **Types go after a colon, everywhere.** `var x: int`, `func f(a: int): string`, > `struct S { x: float }`. If you forget, the compiler tells you what to add. ## The basic types | Type | Example | Notes | |------|---------|-------| | `int` | `42` | 64-bit whole number | | `float` | `3.14` | 64-bit decimal number | | `bool` | `true`, `false` | | | `char` | `'a'` | one character (see below) | | `string` | `"text"` | UTF-8 text, can't be changed in place | | `error` | `error("oops")` | see [Errors and nil](07-errors-and-nil.md) | Sized numbers exist for when you need exact control: `i8 i16 i32 u8 u16 u32 u64 f32` (`i64` is the same as `int`, `f64` the same as `float`). ```rex func main() { var small: u8 = 200 var wrapped = small + 100 // whole numbers wrap around: 300 - 256 print(wrapped) var x = 7 var y = 2 print(x / y, x % y) // whole-number division print(float(x) / float(y)) // convert before dividing for a decimal answer } ``` ```text 44 3 1 3.5 ``` Rules worth remembering: - Different number types never mix. Convert explicitly: `float(x)`, `int(y)`, `u8(z)`. - A number literal adapts to the type it is used with (`var b: u8 = 5`). - Dividing by zero stops the program with a clear message. - Converting a float to an integer cuts off the decimals. - Whole numbers can be written in hex, binary or octal: `0xff`, `0b1010`, `0o755`. `_` may separate digits: `1_000_000`. ### Bits For flags, colors, hashes and file formats, whole numbers have bit operators: | | | | |--|--|--| | `a & b` | and | bits set in both | | `a \| b` | or | bits set in either | | `a ^ b` | xor | bits set in one but not the other | | `~a` | not | every bit flipped | | `a << n` | shift left | same as `a * 2ⁿ` (bits pushed out are lost) | | `a >> n` | shift right | same as `a / 2ⁿ`, rounding down | Each has an assignment form too: `&= |= ^= <<= >>=`. ```rex const BOLD = 0b001 const ITALIC = 0b010 const UNDERLINE = 0b100 func main() { var style = BOLD | UNDERLINE print(style & ITALIC != 0, style & UNDERLINE != 0) style ^= BOLD // switch bold off print(style) var color: u32 = 0xff8800 var red = color >> 16 & 0xff var green = color >> 8 & 0xff print(red, green, 1 << 10, ~0) } ``` ```text false true 4 255 136 1024 -1 ``` - `&` and the shifts bind like `*`, `|` and `^` like `+`, so `x & 1 == 0` means `(x & 1) == 0`. - They work on whole numbers only (`int`, `u8`, ...). For `bool` use `&&` and `||`. - Shifting by the number's width or more gives 0 (or -1 for `>>` of a negative number); shifting by a negative amount stops the program. ## Strings Put values inside text with `{ }`. Write a literal brace as `\{`. ```rex func main() { var name = "Ada" var age = 36 print("Hello {name}, next year you are {age + 1}.") print("tab\there, quote \" and brace \{ok}") var s = "Hello" + ", " + "world" print(s.len(), s.upper(), s.contains("wor")) } ``` ```text Hello Ada, next year you are 37. tab here, quote " and brace {ok} 12 HELLO, WORLD true ``` Handy string methods: `len upper lower trim split lines fields replace repeat contains starts_with ends_with index_of to_int to_float`. See the [cheatsheet](11-cheatsheet.md). ### Slicing `s[a..b]` is the part from byte `a` up to (not including) `b`. Leave a side out to go to the edge. ```rex func main() { var s = "hello world" print(s[0..5]) print(s[6..]) print(s[..5]) } ``` ```text hello world hello ``` A slice outside the string stops the program with a message that shows the length. `s.len()` counts bytes, so a letter like `é` counts as 2. ### Characters: `char` A `char` is **one character**, written with single quotes. Double quotes are for text. ```rex func main() { var c = 'a' print(c, c == 'a', c < 'b') print('é', '\n' == '\n') // any Unicode character; escapes: \n \t \r \0 \\ \' print(int('a'), char(66)) // a character and its number print(string(c) + "!") // a character as text: string(c), or "{c}" } ``` ```text a true true é true 97 B a! ``` Going through a string gives characters: ```rex func main() { var s = "héllo 42" var letters = 0 var digits = 0 for c in s { if c.is_letter() { letters += 1 } if c.is_digit() { digits += 1 } } print(letters, digits) for i, c in "aé!" { print(i, c) } // i is the byte position print(s[0], s[1], s[3]) // s[i] is the character that starts at byte i } ``` ```text 5 2 0 a 1 é 3 ! h é l ``` - `s.chars()` gives all the characters as a list (`[]char`), so you can index it by character number: `var cs = "héllo".chars()` then `cs[1]` is `é` and `cs.len()` is 5. - `for c in s` walks whole characters, even multi-byte ones like `é` or `😀`. - `s[i]` takes a **byte** position. If the position is in the middle of a character, or outside the string, the program stops with a message. For plain English text, position and character number are the same. - Strings can't be changed in place, so `s[0] = 'x'` is an error. Build a new string: `up += string(c.upper())`. - Methods: `is_digit is_letter is_alnum is_space is_upper is_lower upper lower`. (`upper`/`lower` change plain English letters.) - `char` can be compared (`== != < > <= >=`), matched with `match`, and used as a map key. It does no arithmetic: use `int(c)` and `char(n)` if you need that. ```rex func kind(c: char): string { return match c { '+' => "plus" ' ' => "space" _ => "other" } } func main() { var counts: map[char, int] = {} for c in "banana" { counts[c] += 1 } print(counts, kind('+'), kind('x')) } ``` ```text {b: 1, a: 3, n: 2} plus other ``` ### Comparing `==`, `!=`, `<`, `>` work on strings (alphabetical order). Next: [Control flow](03-control-flow.md)