3 ms·
> how do you deal with the lack of optional type or narrowing? The idiomatic way is to return an error or an `ok` boolean at the function boundary. Callers alw
by klabb3 3y ago
> how do you deal with the lack of optional type or narrowing?
The idiomatic way is to return an error or an `ok` boolean at the function boundary. Callers always check return value anyway, this is hard to forget because it’s almost always needed anyway.
The type itself can be value or pointer – its an orthogonal choice. If you have a value type that you return, then you should return the zero value (for instance `time.Time{}`. Both nil and the zero type are comparable by equality check.
This is not ideal, and gets messy when the zero type is a valid value for instance. Generics offer some hope but they are not as capable as in eg Rust.
- wrcwill 3y agoyeah, is there a way to deserialize using (val, err) instead of *val when the field is optional?
- klabb3 3y agoHmm, are we talking json parsing? Yes, the field would take the zero value. If you need to differentiate between the zero-value (eg empty string, 0 for numbers) you’d typically use a pointer only for that purpose. That kinda sucks but there are some good arguments for zero-defaults too. The unmarshal functions take a reference but they don’t need to be declared as (heap-based) pointers. You can pass a `&val` directly. It needs a reference passed in to determine the type.
- wrcwill 3y agoyeah i meant if each field could be a tuple of (val, bool) or (val, err) to get around the pointer issue
- klabb3 3y agoThere are no tuples in Go. Very unfortunate. Tuples, enums and pattern matching is sooo good in Rust. I really miss it in Go.
- deleted 3y ago[deleted]
- throw-the-towel 3y agoJust for curiosity's sake, what good arguments for zero-defaults exist?