by JamesSwift · 1y ago · 0 comments
I only see this blurb in a linked article:
> But Rust has no equivalent of handle: the convenience of the ? operator comes with the likely omission of proper handling.
But I fail to see how having convenience equates to ignoring the error. Thats basically half of my problem with Go's approach, that nothing enforces anything about the result and only minimally enforces checking the error. eg this results in 'declared and not used: err'
x, err := strconv.Atoi("123")
fmt.Println("result:", x)
but this runs just fine (and you will have no idea because of the default 0 value for `y`): x, err := strconv.Atoi("123")
if err != nil {
panic(err)
}
y, err := strconv.Atoi("1234")
fmt.Println("result:", x, y)
this also compiles and runs just fine but again you would have no idea something was wrong x, err := strconv.Atoi("123")
if err != nil {
}
fmt.Println("result:", x)
Making the return be `result` _enforces_ that you have to make a decision. Who cares if someone yolos a `!` or conveniently uses `?` but doesnt handle the error case. Are you going to forbid `panic` too?Nothing prevents adding union types with a zero value. Sure it sucks, but so do universal zero values in pretty much every other situation so that's not really a change.
It's weird, but does align with design decisions that have already been made.
So if there was an `Option[T]` with variants `None` and `Some[T]`, the zero value would be `None` because that's the zero-th variant
In fact the lack of sum types seems to be why you need everything to have a zero value in the first place: because sums are products you need a nonsensical value when the sum is the other type.
I don't think that's the case in Go: whereas I got the impression the C# team started souring on default() after generics landed (possibly because nullable value types landed alongside and they found out that worked just fine and there was no reason nullable reference types wouldn't) I don't really get that impression from the Go team, even less so from them still mostly being Googlers (proto3 removed both required fields and explicit default values).
This bonkers design decision is, as far as I can tell, the underlying infectious cause of nearly every real issue with the language.
The convenience of writing `?` means nobody will bother wrapping errors anymore. Is what I understand of this extremely dubious argument.
Since you could just design your `?` to encourage wrapping instead.
Which is exactly what Rust does -- if the error returned by the function does not match the error type of `?` expression, but the error can be converted using the `From` trait, then the conversion is automatically performed. You can write out the conversion implementation manually, or derive it with a crate like thiserror:
#[derive(Error)]
enum MyError {
#[error("Failed to read file")
IoError(#[from] std::io::Error)
// ...
}
fn foo() -> Result<(), MyError> {
let data = std::fs::read("/some/file")?;
// ...
}
You can also use helper methods on Result (like `map_err`) for inserting explicit conversions between error types: fn foo() -> Result<(), MyError> {
let data = std::fs::read("/some/file").map_err(MyError::IoError)?;
// ...
}2. Idiomatic go type erases errors, so you're converting from `error` to `error`, hence type-directed conversions are not even remotely an option.
.map_err(|e| format!("Failed to read file: {e}")?;
But the "idiomatic Go" way of doing things sounds a lot closer to anyhow in Rust, which provides convenience utilities for dealing with type-erased errors: use anyhow::{Result, Context};
fn foo() -> Result<()> {
let data = std::fs::read("/some/file").context("Failed to read file")?;
// ...
}In practice, the error type will be defined quite close to where the conversion is applied, so the static nature of it doesn’t feel too big.
A thread from two days ago bemoans this point:
Mostly because it is not entirely clear what the Rust-style equivalent in Go might be. What would Rust's "From" look like, for example?
Idiomatic Go type-erases error types into `error`, when there is even a known type in the first place.
Thus `From` is not a consideration, because the only `From` you need is
impl<'a, E> From<E> for Box<dyn Error + 'a>
where
E: Error + 'a,
and that means you can just build that in and nothing else (and it's really already built-in by the implicit upcasting of values into interfaces).That's clearly not true.
type MyError struct{}
func (MyError) Error() string { return "MyError" }
func main() {
var err error = MyError{}
fmt.Printf("%T\n", err) // Output: main.MyError
}
The idea doesn't even make any sense. How could you even begin to handle errors in a meaningful way if you were unable to discern what type the error is?That said, the other responder points out why the sum type approach is not favored (which is news to me, since like I said I havent followed the discussion)
res := someFunc() // func() any
switch v := res.(type) {
case error:
// handle error
case T:
// handle result
default:
panic("unexpected type!")
}
Then, presumably, a T|error sum type would be a specialization of the any type that would allow you to safely eliminate the default arm of the switch statement (or so I would like to think -- but the zero value issue rears its ugly head here too). Personally, I'd also like to see a refinement of type switches, to allow different variable names for each arm, resulting in something like the following hypothetical syntax: switch someFunc().(type) {
case err := error:
// handle error
case res := T:
// handle result
}
However, there's no real syntactic benefit for error handling to be found here. I like it (I want discriminated unions too), but it's really tangential to the problem. I'd honestly prefer it more for other purposes than errors.Just more of the pitfalls of it not being clear how Rust-style applies to an entirely different language with an entirely different view of the world.
x, err := strconv.Atoi("this is invalid")
On the contrary, `x` is _lying_ to you about being useful and you have absolutely no idea if the string was "0" or "not zero"- It isn't easily breakpointable.
- It favors "bubbling up" as-is over enriching or handling.
x, err := strconv.Atoi("123")
if err != nil {
panic(err)
}
y, err := strconv.Atoi("1234")
fmt.Println("result:", x, y)
> this also compiles and runs just fine but again you would have no idea something was wrongOkay, I don't use golang... but I thought ":=" was "single statement declare-and-assign".
Is it not redeclaring "err" in your example on line 5, and therefore the new "err" variable (that would shadow the old err variable) should be considered unused and fail with 'declared and not used: err'
Or does := just do vanilla assignment if the variable already exists?
> There are exceptions to this rule in areas with high “foot traffic”: assignments come to mind. Ironically, the ability to redeclare a variable in short variable declarations (:=) was introduced to address a problem that arose because of error handling: without redeclarations, sequences of error checks require a differently named err variable for each check (or additional separate variable declarations)
go vet and this massive collection of linters bundled into a single binary are very popular: https://golangci-lint.run
linters will warn you of accidental shadowing, among many other things.
FWIW it is never a shadowing declaration. It is at least one non-shadowing declaration plus any number of reassignments.
The fun part is the tendency to keep reassigning to `err` makes the unused variable largely useless, so it’s just there to be a pain in the ass, and your need a separate lint anyway.
If you’re willing to share, I’m very curious to see a code example of what you mean by this.
I ripped most of it off of someone else, link in the gist
interface Result[T] {
IsOk(): bool
IsErr(): bool
Unwrap(): T
UnwrapError(): error
}
// Ok is a Result that represents a successful operation.
struct Ok[T] {
Value: T
}
func Ok[T](value T) Result[T] {
return Ok[T]{Value: value}
}
func (s Ok[T]) IsOk() bool {
return true
}
func (s Ok[T]) IsErr() bool {
return false
}
func (s Ok[T]) Unwrap() T {
return s.Value
}
func (s Ok[T]) UnwrapError() error {
panic("UnwrapError called on Ok")
}
// Err is a Result that represents a failed operation.
struct Err[T] {
Reason: error
}
func Err[T](reason error) Result[T] {
return Err[T]{Reason: reason}
}
func (e Err[T]) Error() string {
return e.Reason.Error()
}
func (e Err[T]) IsOk() bool {
return false
}
func (e Err[T]) IsErr() bool {
return true
}
func (e Err[T]) Unwrap() T {
panic(fmt.Errorf("Unwrap called on Err: %w", e.Reason))
}
func (e Err[T]) UnwrapError() error {
return e.Reason
}