首页 > 解决方案 > 是否可以在 CueLang 中扩展定义

问题描述

是否可以扩展定义?

例如,假设我们想要这样的连接定义

Connection :: {
    protocol: "tcp" | "udp"
    port: int
    host: string
}

我们也希望SecureConnection拥有一切Connection,但我们也喜欢添加用户名和密码。如何做到这一点?

我可以这样做

Connection :: {
    protocol: "tcp" | "udp"
    port: int
    host: string
    ...
}

SecureConnection :: Connection & {
    username: string & >""
    password: string & >""
}

它会起作用,但这也意味着它没有关闭。由于Connection定义中的三个点,我们可以添加任何我们想要保护连接的内容

例如

tcp: SecureConnection & {
    protocol: "tcp"
    port: 8080
    host: "localhost"
    username: "guest"
    password: "guest"
    test: "testing"
    oneUnimportantVariable: "I am not important"
}

当我运行cue export myfile.cue这将给我以下 JSON

{
    "tcp": {
        "protocol": "tcp",
        "port": 8080,
        "host": "localhost",
        "username": "guest",
        "password": "guest",
        "test": "testing",
        "oneUnimportantVariable": "I am not important"
    }
}

那么,如何扩展Connection定义和创建SecureConnection定义,并且不能指定任何未在此定义中指定的变量呢?

标签: schemacuelang

解决方案


您可以使用如下定义嵌入

Connection :: {
    protocol: "tcp" | "udp"
    port: int
    host: string
}

SecureConnection :: {
    Connection
    username: string & >""
    password: string & >""
}

推荐阅读