Skip to content

C error in for _, i in generic array requesting to set mut i #24360

@jorgeluismireles

Description

@jorgeluismireles

Describe the bug

Next function can't be compiled as compiler request i to set as mutable:

fn value_array_resp[T](mut t T, r []u8) {
	$if T is []ValueMenu {
		for _, i in t {
			i.resp(r)
		}
	}
}
Can't run code. The server returned an error:
code.v:18:3: error: `i` is immutable, declare it with `mut` to make it mutable
   16 |     $if T is []ValueMenu {
   17 |         for _, i in t {
   18 |             i.resp(r)
      |         ^

After changing for line to for _, mut i in t { we got a C error.

Reproduction Steps

struct ValueMenu {
	name string
}

fn (mut v ValueMenu) resp(resp []u8) {
	println('menu ${v.name} ${resp}')
}

fn value_resp[T](mut t T, r []u8) {
	$if T is $array {
		value_array_resp(mut t, r)
	}
}

fn value_array_resp[T](mut t T, r []u8) {
	$if T is []ValueMenu {
		for _, mut i in t { // mut i -> C error
			i.resp(r)
		}
		//for i := 0; i < t.len; i++ { // WORKAROUND
		//	t[i].resp(r)
		//}
	}
}

struct Colors {
mut:
	normal []ValueMenu = [ ValueMenu{ 'blink' }, ValueMenu{ 'hue' } ]
}

fn (c &Colors) resp(resp []u8) {
	$for f in c.fields {
		mut m := c.$(f.name)
		value_resp(mut m, resp)
    }
}

fn main() {
	colors := &Colors{}
	colors.resp([ u8(0), 1, 2 ])
}

Expected Behavior

menu blink [0, 1, 2]
menu hue [0, 1, 2]

Current Behavior

Running code...
Can't run code. The server returned an error:
/box/code.v:18: error: cannot convert 'void *' to 'struct main__ValueMenu'

Possible Solution

Workaround:

fn value_array_resp[T](mut t T, r []u8) {
	$if T is []ValueMenu {
		//for _, i in t { // mut i -> C error
		//	i.resp(r)
		//}
		for i := 0; i < t.len; i++ { // WORKAROUND
			t[i].resp(r)
		}
	}
}
menu blink [0, 1, 2]
menu hue [0, 1, 2]

Additional Information/Context

No response

V version

V 0.4.10 0897939

Environment details (OS name and version, etc.)

https://play.vlang.io/p/34d4cae2ee

Note

You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.

Metadata

Metadata

Assignees

Labels

BugThis tag is applied to issues which reports bugs.Generics[T]Bugs/feature requests, that are related to the V generics.Status: ConfirmedThis bug has been confirmed to be valid by a contributor.Unit: cgenBugs/feature requests, that are related to the default C generating backend.

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions