by malcolmstill · 3y ago · 0 comments
If you end up with a long::run::of::module::names, I find it all just blurs into one.
Also this is an no-win situation. C++, Ruby, Perl, and others have used `::` as module-scoping syntax for decades. If Rust does something novel, it's penalized for being unfamiliar. If Rust uses syntax for which there's ample prior art, it's apparently line noise. If rust used a `.` as a separator, it's unclear if you're descending into modules or calling a function chain.
There's literally no way to win.
This is especially true when there's similarly named items from different paths. Best example is `Result`/`Error` types. eg: std::io::Result vs normal default Result vs other crate's Result type. Another example would be math types like Vec2 between game engine and egui. String in mlua vs std rust etc..
Usually you can get around this by importing it with a different name like `use mlua::String as LuaString`. but it is still something that you need to actively do.
> If rust used a `.` as a separator, it's unclear if you're descending into modules or calling a function chain
Interestingly, from the zig documentation:
Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. @import returns the struct type corresponding to the file.
This means that there isn't really any difference between accessing a struct field and accessing something in module...the module is also a kind of struct (and rust, as in zig, differentiating struct field access vs function invocation is possible because of the parens in the latter).Yes there is? Follow what C#, F#, Java, TypeScript, etc. do
If I was to think about it: comparing rust to zig, zig benefits a lot from error and optional types having their own syntax rather than being treated like any other type. For example a return type of:
Result<Option<usize>, Error>>
in rust is rendered (mostly) equivalently in zig as !?usize
Note: there are some options in rust for cleaning up errors such as the anyhow library.Disclaimer: I'm a zig fan and contribute monetarily so please weight anything I say on zig vs rust with that in mind. (I do write rust at work though)
fn someFunction(a: usize) !usize {
if (a < 10) return error.LessThanTen;
const b = try anotherFunction(a);
return 2 * b;
}
fn anotherFunction(x: usize) !usize {
if (x < 20) return error.LessThanTwenty;
return x * 3;
}
The compiler infers the error type of `someFunction` as: error {
LessThanTen,
LessThanTwenty
}
When you then `switch` on an error type, the compiler will exhaustively check that you have handled all the cases.Note the "(mostly) equivalently" was a reference to the fact that Zig errors can't (currently) contain any other information, whereas an error in rust can carry other information.
Also note that the compiler can't infer the error type in all case, for example in the case of a recursive function. In that case you do need to explicitly write out the error set.