v icon indicating copy to clipboard operation
v copied to clipboard

type alias for 2D array generates compile time error

Open pd-giz-dave opened this issue 1 year ago • 4 comments

Describe the bug

This does not compile:

module main

pub type Labels = [][]int

pub fn new_labels(width int, height int) Labels {
	//mut labels := [][]int{len: height, init: []int{len: width}}  // compiles OK
	mut labels := Labels{len: height, init: []int{len: width}}  // does not compile
	return labels
}

fn main() {
	mut labels := new_labels(2,2)
}

Reproduction Steps

Try to compile the above code.

Expected Behavior

I would expect it to compile with no error.

Current Behavior

Get compiler error:

issues/complier_error.v:6:16: error: alias type name: [][]int is not struct type
    4 | 
    5 | pub fn new_labels(width int, height int) Labels {
    6 |     mut labels := Labels{len: height, init: []int{len: width}}
      |                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    7 |     return labels
    8 | }

Possible Solution

Either fix or update documentation to say its not allowed.

Additional Information/Context

No response

V version

V 0.4.4 ac2dcc2

Environment details (OS name and version, etc.)

EndeavourOS

[!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.

pd-giz-dave avatar Feb 02 '24 21:02 pd-giz-dave

@pd-giz-dave because you assign at the labels var in your function a struct that does not exist ( struct assignation declaration in your example ) and you trying to return it. Moreover, return type of your function is not a struct.

It's not a bug.

GGRei avatar Feb 05 '24 04:02 GGRei

The type alias documentation is this: "Type aliases To define a new type NewType as an alias for ExistingType, do type NewType = ExistingType. This is a special case of a sum type declaration." So is "[][]int" not a type? I'm a newbie to V so I niaively interpreted a type alias like a C #define, ie. anywhere where ExistingType is valid so would NewType be. My understanding is clearly wrong, but a fuller explanation in the docs would help.

pd-giz-dave avatar Feb 05 '24 13:02 pd-giz-dave

No, you are correct, you have just run into a bug.

JalonSolov avatar Feb 05 '24 14:02 JalonSolov

If we change array to map on Labels, we'll get:

bug.v:7:16: error: direct map alias init is not possible, use Labels(map[int]string{}) instead

So, if we want to support array init via this struct way, probably we should support map too for consistency.

felipensp avatar Feb 09 '24 12:02 felipensp