Variables & basic types
Declare values, work with numbers, and make conversions explicit.
Declarations and inference#
Use name: Type for an explicit variable declaration, or name := value to infer its type. A declaration without an initializer, such as x: int;, receives its type’s default value: zero for an integer, for example. A name declared in an inner block can shadow an outer name.
Neither form of variable declaration makes a variable immutable. After declaration, use = or a compound assignment such as += to change its value. The new value must remain compatible with the variable’s type.
A block creates a lexical scope. A local name is available from its declaration within that scope, including nested blocks unless another declaration shadows it. Prefer a different name when shadowing would make it unclear which value an expression uses.
count := 12;
depth: float = 42.5;
ready: bool; // false
count += 3;
count++;
Here, count is inferred as int, depth is explicitly a float, and ready starts as false. The two updates leave count equal to 16. Use count = ... for another assignment; another declaration is a different operation.
Built-in scalar types#
int and i64 are signed 64-bit integers. i32, i16, and i8 provide narrower signed storage. uint, u64, u32, u16, and u8 provide unsigned integers. float and f64 are double precision; f32 is single precision. bool holds true or false. string stores immutable bytes. Choose explicit widths for binary data and C interfaces.
Use int for ordinary integer values unless a storage or interface requirement calls for a particular width. Ocean’s int is 64-bit; it should not be assumed to have the same width as a C int. Floating-point values have different precision and rounding behavior from integers, so choose them for quantities that need fractional values.
An integer literal, including a negative literal, can supply a floating-point value when the surrounding operation expects one: depth == 0 and calls such as measure(2) work when the value or parameter is a float. Typed initializers, assignments, returns, and arithmetic also accept integer literals. Integer variables and expressions such as 1 + 2 still require an explicit cast; count := 0 still infers int.
Integer variables convert implicitly only when the destination can represent every source value. For example, i8 to i32, u8 to u16, and u8 to i16 are allowed. Reducing the storage width or converting a signed integer to an unsigned integer requires value -> Type. An unsigned integer can convert implicitly to a signed integer only when the signed destination has enough bits to represent the unsigned source’s full range. For example, u8 fits in i16, but not in i8. These rules apply to arguments, initializers, assignments, returns, and collection elements. Fitting integer literals can directly supply narrower types (small: i8 = 42), but variables and expressions are checked by their type rather than their current value. Widening an individual number does not change the storage type behind a pointer or inside an existing collection. For example, an i8 value can supply an i32 parameter, but an i8[] array cannot supply an i32[] parameter, and an *i8 pointer cannot supply an *i32 parameter. When integer operands have different widths, arithmetic uses a compatible 64-bit result type. A fitting integer literal can instead use the other operand’s type. Mixed signed/unsigned arithmetic requires a cast when no signed 64-bit type represents both ranges.
An arrow cast, written value -> Type, requests an explicit conversion. It makes a type change visible at the expression where it occurs. For a compound target such as a pointer type, put the target in parentheses.
| Type | Meaning |
|---|---|
int, i64 | Signed 64-bit integer |
i32, i16, i8 | Signed 32-, 16-, and 8-bit integers |
uint, u64 | Unsigned 64-bit integer |
u32, u16, u8 | Unsigned 32-, 16-, and 8-bit integers |
float, f64 | Double-precision floating point |
f32 | Single-precision floating point |
bool | true or false |
string | Immutable sequence of bytes |
small: i8 = 7;
wide: i32 = small;
narrow := wide -> i8;
ratio := 3.5;
whole := ratio -> int;
nonzero := whole -> bool;
Assigning small to wide implicitly widens an i8 to i32. Converting wide back to i8 requires the explicit arrow cast. Converting 3.5 to int produces an integer, and converting a number to bool tests whether it is nonzero. A cast can lose information; choose the destination type according to the values your program needs to represent.
Operators#
Arithmetic uses +, -, *, /, and %. Comparisons use ==, !=, <, <=, >, and >=. Boolean && and || short-circuit: the right operand is evaluated only when needed. Integer bit operations are supported. The conditional expression uses condition ? yes : no.
Use parentheses when an expression combines several operations and their grouping would otherwise be hard to follow. Short-circuit evaluation is especially useful for guards: a condition can establish that a later expression is safe before the expression is evaluated.
The conditional expression produces one of two values. It is useful for a small choice inside an assignment, such as choosing a label. For branches that perform several operations, use an if statement instead so each path remains easy to read.
label := count > 10 ? "many" : "few";
safe := count != 0 && 100 / count > 2;
In the second expression, the division is evaluated only when count is nonzero. This guard prevents division by zero. The label expression chooses "many" or "few"; both alternatives are strings, so the result has a consistent type.
Equality works recursively on structs and arrays and is available on unconstrained generic types. Strings also support <, <=, >, and >= using unsigned-byte lexicographic order, including embedded NUL bytes. If one string is an exact byte prefix of another, the shorter string comes first; for example, "a" < "aa".
Default values#
zero(Type) explicitly constructs a default value. Its argument is a type, not a value. Each struct field receives the default for its own type, strings and dynamic arrays are empty, maps contain no entries, numbers are 0, and booleans are false.
Default initialization lets you declare a counter, flag, or empty collection without writing a literal initializer. zero(Type) is useful when you want to express the same default explicitly, especially in generic code where the concrete type is a parameter. It constructs a value; it does not call a user-defined constructor.
For a struct, defaulting proceeds through its stored fields. For a fixed buffer, every element receives a default value. An empty string, dynamic array, or map is a valid value with length zero. It can be used without first assigning a nonempty value.
count := zero(int);
text := zero(string);
items := zero(int[]);
Notice that zero(int[]) takes the array type itself. Passing a variable to zero is not an alternative spelling for clearing it. A reset is an assignment such as count = zero(int);. Pointer defaults need extra care because the zero address and explicit null are distinct in Ocean.
Value equality and generic comparisons#
== and != are available for every generic type parameter, including an unconstrained T; no comparability constraint is required. This allows a generic function to test two values for equality without declaring a special “comparable” constraint. It does not allow arbitrary unrelated types to be compared: the operands still have to satisfy Ocean’s usual type-compatibility rules, including its pointer and explicit-null rules.
Struct equality recursively compares stored fields, ignoring padding. Arrays compare lengths and then elements recursively, including nested arrays and structs. Capacity and allocation address do not affect array equality. A fixed array, an array whose length is chosen at runtime, and a dynamic array can be compared when both operands store the same element type. Equal lengths and equal elements are required for equality. A difference in length makes the arrays unequal. Fixed raw buffers compare their elements; raw buffer pointer views and typed pointers compare addresses, without following pointees. Maps compare their key/value entries, ignoring insertion order and bucket capacity. Enum value equality compares which variant is stored and the data carried by that variant; comparison with a variant selector, such as event == Event.Key, tests only the tag. Function values compare the function code and the particular captured-variable environment they refer to. Copying a closure preserves that identity; creating a new closure with its own captured variables does not.
An any or interface value stores both a value and its concrete type; this representation is called a box. Equality inspects that concrete type to choose how to compare the stored values. Matching concrete types compare by the rules above; different types compare unequal, except primitive numeric values retain the usual numeric conversions. Floating-point equality is numeric even inside aggregates: positive and negative zero are equal, and NaN is unequal to itself. Both operands are evaluated once, left to right; the left value is preserved if the right expression mutates it.
Strings support all six comparisons: ==, !=, <, <=, >, and >=. Ordering compares unsigned bytes from left to right, including embedded zero (NUL) bytes. The first differing byte decides the order. If every byte of the shorter string matches the start of the longer string, the shorter string comes first. It is case-sensitive and does not perform locale collation or Unicode normalization. String constraints, including T string, support ordering. An unconstrained T promises equality but does not promise ordering or arithmetic.
func indexOf<T>(data array<T>, value T) int {
for (i := 0; i < len(data); i++) {
if (data[i] == value) return i;
}
return -1;
}
struct Person { name string; age int; }
func main() int {
people := Person[2]{{"Ada", 36}, {"Lin", 28}};
if (indexOf<Person>(people, Person{"Lin", 28}) != 1) return 1;
if (!("apple" < "banana" && "a" < "aa")) return 2;
return 0;
}
indexOf<Person> works because Ocean compares both stored fields of each Person. It returns 1 for the second array element. The string tests show both a differing first byte (apple versus banana) and an exact-prefix comparison (a versus aa).