Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare nullable field in Nim?

Tags:

nim-lang

The stock_symbol is optional, it exists only for some companies, what would be proper way to declare it in Nim?

Do I have to use ref or there's other way?

type
  Company = object
    name:         string
    stock_symbol: string

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

And similar question for composite type, usually you need to know both stock exchange and the symbol

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)
like image 759
Alex Craft Avatar asked Oct 19 '25 21:10

Alex Craft


1 Answers

Seems like Option[T] should be used

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))

and

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))
like image 150
Alex Craft Avatar answered Oct 22 '25 18:10

Alex Craft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!