Type Casting (as)
saQut does not perform implicit type conversions. To turn an int into a
float, or a string into an int, you write the conversion explicitly with
the as operator.
Basic conversions
Section titled “Basic conversions”int a = 42;float b = a as float; // 42.0int c = 3; // (int)3float d = c as float; // 3.0, not 3The as operator makes the conversion explicit. There is no hidden promotion
from int to float during arithmetic: if you divide two integers, you get
integer division. If you want float division, cast one of them first.
Numeric conversions
Section titled “Numeric conversions”| From | To | Behavior |
|---|---|---|
int |
float |
Widening, always safe |
float |
int |
Truncates toward zero |
int |
byte |
Fail if out of 0-255 range |
byte |
int |
Widening, always safe |
int |
bool |
0 becomes false, non-zero becomes true |
bool |
int |
false becomes 0, true becomes 1 |
float pi = 3.99;int n = pi as int; // 3 (truncated)
byte b = 200;int i = b as int; // 200
int big = 300;// byte small = big as byte; // runtime error: out of rangeString conversions
Section titled “String conversions”Numbers can be parsed from strings. When the conversion might fail, cast to a nullable target:
string s = "42";int? n = s as int?; // 42if (n != null) { print(n); }
string t = "hello";int? m = t as int?; // null (not a number)Floats work the same way:
string s = "3.14";float? f = s as float?; // 3.14Converting to string
Section titled “Converting to string”Any type can be cast to string:
int a = 42;string s = a as string; // "42"
float f = 3.14;string t = f as string; // "3.14"
bool b = true;string u = b as string; // "true"Struct conversions
Section titled “Struct conversions”You cannot cast between different struct types. Each struct has its own layout; there is no automatic conversion.
struct Point { int x; int y; }struct Vector { int x; int y; }
Point p = Point(1, 2);// Vector v = p as Vector; // compile errorSummary
Section titled “Summary”asis the only type conversion operator in saQut- Int to float widens; float to int truncates
- String parsing returns
nullon failure when cast to nullable - Any type can become
stringwithas string - Structs cannot be cast between each other
