Golang - Unexpected behavior with multiple tasks

I am writing a Go function that mimics Python's itertools.permutations() , but returns all permutations at once, rather than giving one at a time.

I see unexpected behavior while updating two variables in the following lines of code:

 setcopy := append([]int(nil), sorted...) for i := 0; i < r; i++ { c := counters[r-1-i] current[i], setcopy = setcopy[c], append(setcopy[:c], setcopy[c+1:]...) } 

I get the correct results when disabling the above update:

 current[i] = setcopy[c] setcopy = append(setcopy[:c], setcopy[c+1:]...) 

I was mostly inspired by the Pop and Delete examples from the SliceTricks article. Is there a significant difference between what I am trying to do and what?

If you want to check the complete code (including an example of faulty output and some print instructions for debugging), you can check this Gist .

+6
source share
1 answer

Go programming language specification

Assignments

The appointment continues in two stages. Firstly, expression index operands and pointers (including an implicit pointer pointers in selectors) on the left and expressions on the right are evaluated in the usual way. Secondly, tasks are performed in order from left to right.

Opends

Operands denote elementary values ​​in an expression. The operand can be a literal, (possibly qualified) non-empty identifier, denoting a constant, variable or function, a method expression, giving a function or expression in brackets.

Assessment Procedure

When evaluating the operands of an expression, assignment, or return, an operator, all function calls, method calls, and operation relationships are evaluated in lexical order from left to right.

For example, in the destination (function-local)

 y[f()], ok = g(h(), i()+x[j()], <-c), k() 

function calls and communication occur in the order f (), h (), i (), j (), <-c, g () and k (). However, the order of these events in comparison with the estimate and indexation of x and the estimate of y is not indicated.

Adding and copying fragments

If the capacitance s is not large enough to correspond to additional values, append allocates a new, sufficiently large base array that fits both existing slice elements and additional values. Otherwise, append reuses the underlying array.

Is a new base array allocated?

Assignment operator

 current[i], setcopy = setcopy[c], append(setcopy[:c], setcopy[c+1:]...) 

seems equivalent

 a := append(setcopy[:c], setcopy[c+1:]...) x := setcopy[c] y := a current[i], setcopy = x, y 

but the order of events of the function call in comparison with the evaluation of other operands is not specified ( Order of evaluation ).

+7
source

Source: https://habr.com/ru/post/977481/


All Articles