v
v copied to clipboard
json: Optional objects in structs don't work
Describe the bug
It's not possible to define an optional attribute if the attribute is an object (of some other struct). The code below will not compile and cause a C error during compilation. This is a very useful feature for json encoding actually. Because json encoding struct B in case the valueb is not optional (removing ?) results in always having it present in the json string (with all values default). There are situations where want to not have it in the json string if it was not provided.
pub struct A {
valuea int
valueb ?int
}
pub struct B {
valuea int
valueb ?A //compile issue
}
Expected Behavior
Either allow us to pass optional objects in structs or let the v compiler return a compilation error saying that you cannot have optional attributes in structs unless they are primitive types.
Current Behavior
See description
Reproduction Steps
See description
Possible Solution
See description
Additional Information/Context
No response
V version
V 0.3.2 2c78078
Environment details (OS name and version, etc.)
OS: linux, Ubuntu 22.04.1 LTS Processor: 16 cpus, 64bit, little endian, 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz CC version: cc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
getwd: /work/farmerbot vmodules: /home/brandon/.vmodules vroot: /work/v vexe: /work/v/v vexe mtime: 2023-01-18 13:03:15 is vroot writable: true is vmodules writable: true V full version: V 0.3.2 f0a252d.2c78078
Git version: git version 2.34.1 Git vroot status: weekly.2023.03-15-g2c780788 (226 commit(s) behind V master) .git/config present: true thirdparty/tcc status: thirdparty-linux-amd64 12f392c3
Hi, running your code in the V Playground I get this compilation error:
code.v:1:12: error: single letter capital names are reserved for generic template types.
1 | pub struct A {
| ^
2 | valuea int
3 | valueb ?int
Exited with error status 1
Renaming your structs with a 3 letter name (for example calling them Abd and Def) all seems to work. Hope this helps. Bye
You have an old V version. Make sure to use the latest one. It should work there.
It actually happens when json encoding the object:
import json
pub struct MyStruct {
pub mut:
valuea int
}
pub struct MyStruct2 {
pub mut:
valuea int
valueb ?MyStruct
}
json.encode(MyStruct2{valuea:1}) // compilation crash
ok, so it seems something more related to json, it could be useful to rename this issue