nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.23k stars 1.47k forks source link

Cannot instantiate generic type with not nil parameter type #19014

Closed iacore closed 2 years ago

iacore commented 2 years ago

Function echo outputs the wrong string.

Example

{.experimental: "notnil".}
import tables

type FooObject = object
type Foo = ref FooObject not nil
type Bar = object
    table: Table[int, Foo]

proc `=init`(x: var Foo) =
    x = new(Foo)

let bar = Bar()

Current Output

> nim c -r test.nim
Hint: used config file '/home/user/.choosenim/toolchains/nim-#devel/config/nim.cfg' [Conf]
Hint: used config file '/home/user/.choosenim/toolchains/nim-#devel/config/config.nims' [Conf]
...................................................................
/home/user/computing/test/test.nim(12, 14) Error: The Bar type requires the following fields to be initialized: table.

What's wrong

1

There should be some way to specify default value of not nil reference type.

2

The error message doesn't tell why table can't be initialized.

3

let table: Table[int, Foo] = newTable()

yields the compile error

Error: cannot instantiate: 'A'

not

Error: cannot instantiate: 'Foo'

Possible Solution

Use =init hook or some other proc for the default value.

Additional Information

This is related to https://nim-lang.github.io/Nim/manual_experimental_strictnotnil.html This is related to user defined default value.

Nim Compiler Version 1.5.1 [Linux: amd64]
Compiled at 2021-10-15
Copyright (c) 2006-2021 by Andreas Rumpf

git hash: 73330711a3d753d25b073fb1dc24cb16e559724d
active boot switches: -d:release
iacore commented 2 years ago

Trying to instantiate not nil ref type

{.experimental: "notnil".}
import tables

type FooObject = object
type Foo = ref FooObject not nil
type Bar = object
    table: Table[int, Foo]

proc `=init`(x: var Foo) =
    x = new(Foo)

let foo: Foo

Output

Error: 'let' symbol requires an initialization
Araq commented 2 years ago

Use =init hook or some other proc for the default value.

There is no =init hook in today's Nim. The RFC hasn't been implemented.

Error: 'let' symbol requires an initialization

That's not a bug either.