vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.72k stars 2.16k forks source link

type alias for 2D array generates compile time error #20715

Closed pd-giz-dave closed 7 months ago

pd-giz-dave commented 8 months ago

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.

GGRei commented 8 months ago

@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.

pd-giz-dave commented 8 months ago

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.

JalonSolov commented 8 months ago

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

felipensp commented 8 months ago

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

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

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