Thanks again - I'm learning a lot here!

For info, the background here is that I've been writing code like:

  type T struct {
      SomeField int
  }

  func NewTFromJSON(data []byte) (*T, error) {
      var t T
      return &t, json.Unmarshal(data, &t)
  }

which wraps up error handling into a single line. This works when T is a
non-simple type as &t does not change, even if the value of t does.

Writing this with T being a simple type, like int, results in the case
described in the original post:

  // NewIntFromJSON relies on undefined behavior, don't use it!
  func NewIntFromJSON(data []byte) (int, error) {
      var i int
      return i, json.Unmarshal(data, &i)
  }

So, in these cases I will do as Axel suggests and avoid the implicit
dependence on evaluation order.

A go vet check for this would be wonderful, even if it's not perfect. As
long as there aren't any false positives (i.e. warning when the code does
not in fact rely on unspecified behavior), it matters less if there are
false negatives (i.e. not warning when the code actually relies on
unspecified behavior). Maybe a simple test could catch the most common
cases.

On Wed, 15 Jan 2020 at 21:29, Ian Lance Taylor <i...@golang.org> wrote:

> On Wed, Jan 15, 2020 at 12:24 PM Tom Payne <t...@tompayne.org> wrote:
> >
> > Thanks all for the insight and explanation. Could I suggest tweaking the
> Go language specification to emphasize the separation, so it reads:
> >
> >    "when evaluating the operands of an expression, assignment, or return
> statement, then all function calls, method calls, and communication
> operations are evaluated in lexical left-to-right order. Any operands that
> are variables take the value of the variable after all function calls,
> methods calls, and communication operations have been evaluated."
>
> That suggested addition is not correct.  The language deliberately
> does not specify when operands that are variables are evaluated.  They
> may be evaluated before function calls, they may be evaluated after.
> Different Go compilers make different decisions here.
>
> If we decided to specify it, I'm sure we would specify that the
> variables are evaluated in left to right order.
>
> Personally I think one good approach would be a vet check that
> complains about statements that both read and write a variable in an
> unspecified order.  But it's fairly hard to catch all possible cases
> of this.
>
> Ian
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAHY_QbTxpmvS3735HPaDeDy9K7j5VY76CCfh%3D3QsGcA%3D3njVug%40mail.gmail.com.

Reply via email to