Created
June 16, 2018 13:20
-
-
Save nodefish/21b3ddaebe5aeaf48cc76c892aba7366 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn List(comptime T: type) type { | |
return struct { | |
const List_t = this; | |
buf: []T, | |
pub fn init(buf: []T) List_t { | |
return List_t { | |
.buf= buf | |
}; | |
} | |
// intentional isize instead of usize -> if negative, return error | |
pub fn at(self: *List_t, i: isize) !T { | |
if (i < 0) return error.NegativeValue; | |
return self.buf[usize(i)]; | |
} | |
}; | |
} | |
const Item = struct { | |
name: []const u8 | |
}; | |
fn NumberOrError() !i32 { | |
return error.SomethingWentWrong; | |
} | |
pub fn main() void { | |
const warn = @import("std").debug.warn; | |
var buf: [10]Item = undefined; | |
var i: usize = 0; | |
while (i < buf.len) { | |
buf[i] = Item { | |
.name = "Whatever" | |
}; | |
} | |
var item_list = List(Item).init(&buf); | |
var some_item = item_list.at(4); | |
// // Uncomment here and build -- Can't unwrap error from `!Item` | |
// if (some_item) |item| { | |
// warn("{}", item); | |
// } | |
if (NumberOrError()) |val| { | |
warn("It worked!"); | |
} else |err| { | |
warn("Error: {}", @errorName(err)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment