V: Something like any or dynamic type

Created on 4 Feb 2020  Â·  10Comments  Â·  Source: vlang/v

There are scenarios where the type isn't known.

Example: JSON

It should be possible at least:

type JSON = string | int | bool | null | map[string]JSON
Feature Request

Most helpful comment

type JSON = string | int | bool | null | map[string]JSON

Do you think Sum types would suffice?

All 10 comments

I think you asked about this on Discord.

Can you give an example for a typed language that supports it?

Typescript, Golang Dart!, Kotlin, Java. Is this enough?

I'd like to see an actual code example.

Let's take a json example:

{
    "messages": [
        {  "type":  "error"  },
        {  "type": "msg", "content": "Hello World"  },
        {  "something": "other"  }
    ]
}

In this case the content of the message object is unknown. In this case the following examples from other languages are used:

Go:

type Payload struct {
    messages []interface{}
}

Typescript:

type Payload = {
    messages: any[]
}

Kotlin:

class Payload(val messages: Array<Any>)

Dart:

class Payload {
  List<dynamic> messages;
}
// or
class Payload {
  List<Object> messages;
}

My proposal would be:

An any type which supports all types.

struct Payload {
    messages any
}

p := Payload{
    messages: 123456,
}

if typeof p.messages == int {
    // smartcast
    // do anything
}

type JSON = string | int | bool | null | map[string]JSON

Do you think Sum types would suffice?

In this case maybe. But a dynamic type is required for other scenarios i think.

I think this requires reflection. A generic struct allows for compile time type guarantees:

struct Payload<T> {
    messages T
}

p := Payload<int>{
    messages: 123456
}

Yeah, an “any” type in the same manner as “object” or “dynamic” or “id” in other languages is either relying on a different language entirely (as in TypeScript or any lang that compiles to JavaScript) or runtime reflection.

All of the languages that support this construct are either duck-typed or have a managed runtime with a full reflection system and a JITter. V is a strongly typed language and to support an any/dynamic type means the compiler has to pre-generate every possible permutation of types.

I think this is just a fundamental case of having never used a language that is strongly typed without a managed runtime and reflection system. I would suggest doing a little research and reading up on some C code solutions to see what is possible and how C code handles things.

Yes, in most cases you want to update your logic and use static types.

It will be possible to use map[string]any and then type match any, which will be similar to Go's interface{}.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

radare picture radare  Â·  3Comments

vtereshkov picture vtereshkov  Â·  3Comments

ArcDrake picture ArcDrake  Â·  3Comments

penguindark picture penguindark  Â·  3Comments

arg2das picture arg2das  Â·  3Comments