V: 'a, b += foo()' doesn't result in an error

Created on 7 Jul 2020  路  13Comments  路  Source: vlang/v

V version:
latest master with mingw64

OS:
win10

What did you do?

fn foo() (int,int) {
    return 10, 10
}

fn main() {
    mut a, mut b := foo()
    a, b += foo() 
    println(a)
    println(b)
}

What did you expect to see?
compile error

What did you see instead?
10, 10

_And the same applies to -=, *=, /=, ..._

Bug

Most helpful comment

Because it's complicated and confusing, and I've never seen a use case for it.

In very rare situations when you need to do this, just use temp vars.

All 13 comments

it shouldn't compile:

syntax error: unexpected +=, expecting := or = or comma

@medvednikov Then how to write code to achieve a, b += foo()?

a += foo()
b += foo()

@medvednikov
But that would result in assignment mismatch error. foo() returns two values while lhs only has one variable.

x, y := foo()
a += x
b += y

@medvednikov Yes it works, but isn't that kind of verbose? Why not allowing a, b += foo()?

The syntax itself is not very reasonable, we must first give up some special needs.

@medvednikov is right. You can't do this in languages which have multiple assignments.

Go:

package main

import (
    "fmt"
)

func r() (int, int) {
    return 12, 12
}

func main() {
    var a, b = 2, 3
    a, b += r()
    fmt.Println("Hello, playground")
}

Output: syntax error: unexpected +=, expecting := or = or comma

Python:

def foo()
   return 12, 12

a, b = 2, 3
a, b += foo()

Output: SyntaxError: illegal expression for augmented assignment

@Delta456 Thanks for the info! I'm just thinking about why. Is it due to ambiguity? But I didn't come up with such an example.

@SleepyRoy I think it is because you have multiple assignment for declaration and changing values only but not for declare assignments. This works.

>>> mut a, mut b := 2, 3
>>> a, b = a+2, b+2
>>> a
4
>>> b
5
>>> 

@Delta456 Thanks. But I still don't understand why a, b += foo() shouldn't be allowed.

Because it's complicated and confusing, and I've never seen a use case for it.

In very rare situations when you need to do this, just use temp vars.

Actually should keep it open until it results in an error.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

clpo13 picture clpo13  路  3Comments

ArcDrake picture ArcDrake  路  3Comments

markgraydev picture markgraydev  路  3Comments

aurora picture aurora  路  3Comments

vtereshkov picture vtereshkov  路  3Comments