Try try and or_else built-in procedures with operators try and try else

This commit is contained in:
gingerBill
2021-07-04 12:37:21 +01:00
parent a01d6dcea7
commit 4b831dbddd
11 changed files with 335 additions and 307 deletions

View File

@@ -1999,9 +1999,9 @@ relative_data_types :: proc() {
fmt.println(rel_slice[1]);
}
try_and_or_else :: proc() {
fmt.println("\n#try(...) and or_else(...)");
// IMPORTANT NOTE: 'try' and 'or_else' are experimental features and subject to change/removal
try_and_try_else :: proc() {
fmt.println("\n#'try ...'' and 'try ... else ...'");
// IMPORTANT NOTE: 'try' and 'try else' are experimental features and subject to change/removal
Foo :: struct {};
Error :: enum {
@@ -2029,11 +2029,11 @@ try_and_or_else :: proc() {
// 'try' is a lovely shorthand that does this check automatically
// and returns early if necessary
f1 := try(bar(true));
f1 := try bar(true);
fmt.println(#procedure);
fmt.println(f1);
f2 := try(bar(false));
f2 := try bar(false);
fmt.println(#procedure);
fmt.println(f2);
return .None;
@@ -2056,13 +2056,13 @@ try_and_or_else :: proc() {
// The above can be translated into 'try'
i = 1;
f1 := try(bar(true));
f1 := try bar(true);
fmt.println(#procedure);
fmt.println(f1);
i = 2;
f2 := try(bar(false));
f2 := try bar(false);
fmt.println(#procedure);
fmt.println(f2);
@@ -2072,7 +2072,7 @@ try_and_or_else :: proc() {
}
try_return_value4 :: proc() -> (i: int, j: f64, k: bool, err: Error) {
f := try(bar(false));
f := try bar(false);
fmt.println(#procedure);
fmt.println(f);
return 123, 456, true, .None;
@@ -2088,7 +2088,7 @@ try_and_or_else :: proc() {
}
*/
// 'try' equivalent
f2 := try(m["hellope"]);
f2 := try m["hellope"];
fmt.println(f2);
return true;
}
@@ -2109,7 +2109,7 @@ try_and_or_else :: proc() {
assert(a == 0 && b == 0 && c == false && err4 == .Something);
}
{
// 'or_else' does a similar value check as 'try' but instead of doing an
// 'try else' does a similar value check as 'try' but instead of doing an
// early return, it will give a default value to be used instead
m: map[string]int;
@@ -2119,22 +2119,22 @@ try_and_or_else :: proc() {
if i, ok = m["hellope"]; !ok {
i = 123;
}
// The above can be mapped to 'or_else'
i = or_else(m["hellope"], 123);
// The above can be mapped to 'try else'
i = try m["hellope"] else 123;
assert(i == 123);
}
{
// 'or_else' can be used with type assertions too, as they
// 'try else' can be used with type assertions too, as they
// have optional ok semantics
v: union{int, f64};
i: int;
i = or_else(v.(int), 123);
i = or_else(v.?, 123); // Type inference magic
i = try v.(int) else 123;
i = try v.? else 123; // Type inference magic
assert(i == 123);
m: Maybe(int);
i = or_else(m.?, 456);
i = try m.? else 456;
assert(i == 456);
}
}
@@ -2171,6 +2171,6 @@ main :: proc() {
union_maybe();
explicit_context_definition();
relative_data_types();
try_and_or_else();
try_and_try_else();
}
}