如何在 Nim 中声明可为空的字段?

How to declare nullable field in Nim?

stock_symbol是可选的,它只适用于某些公司,在 Nim 中声明它的正确方法是什么?

我必须使用 ref 还是有其他方法?

type
  Company = object
    name:         string
    stock_symbol: string

echo Company(name: "Microsoft", stock_symbol: "MSFT")
echo Company(name: "Kinetic",   stock_symbol: nil)

和复合类型的类似问题,通常你需要知道证券交易所和代码

type
  SymbolWithExchange = object
    exchange: string
    symbol:   string

  Company2 = object
    name:         string
    stock_symbol: SymbolWithExchange

echo Company2(
  name:         "Microsoft", 
  stock_symbol: SymbolWithExchange("NYSE", "MSFT")
)
echo Company2(name: "Kinetic",   stock_symbol: nil)

似乎应该使用 Option[T]

import options

type
  Company = object
    name:         string
    stock_symbol: Option[string]

echo Company(name: "Microsoft", stock_symbol: some("MSFT"))
echo Company(name: "Kinetic",   stock_symbol: none(string))

import options

type
  SymbolWithExchange = object
    exchange: string
    symbol:   string

  Company2 = object
    name:         string
    stock_symbol: Option[SymbolWithExchange]

echo Company2(
  name:         "Microsoft", 
  stock_symbol: some(SymbolWithExchange(exchange: "NYSE", symbol: "MSFT"))
)
echo Company2(name: "Kinetic",   stock_symbol: none(SymbolWithExchange))