3 ms·
> Go's type inference can take: `x, err := 1, someNilStruct` And have that mean either "err is now a nil struct type" or "err is now a non-nil interface". Which
by throwaway894345 5y ago
> Go's type inference can take: `x, err := 1, someNilStruct` And have that mean either "err is now a nil struct type" or "err is now a non-nil interface". Which of those things it does depends on the types of existing variables in scope or function signatures.
You’re mistaken here. `err` will always have exactly the same type as `someNilStruct`. Specifically you’re confusing the variable declaration syntax with the variable assignment syntax. `err := foo` is the same as Rust’s `let mut err = foo` in that `err` will have exactly the same type as `foo` no matter the types of other variables. `err = foo` behaves exactly the same in Go as in Rust in that you’re just reassigning the value of `err` but it’s type doesn’t change.
- anonymoushn 5y agoThe spec says > Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. This suggests that a redeclaration as part of a short assignment will not change the type of the previously-defined err. is the spec incorrect? Edit: Here's a demonstration of this sort of thing https://go.dev/play/p/Po_Uy85ORN_L https://go.dev/play/p/Po_Uy85ORN_L. You can uncomment line 22 to change the meaning of the assignment on line 23 and cause the program to segfault.
- TheDong 5y agoThe playground link I have two comments ago shows exactly the behavior I describe, that multiple assignment exhibits exactly the behavior I describe. Click through to the playground link and add some 'fmt.Printf("%T\n", err)' lines here and there to see what I mean.