I've seen quite a bit of discussion about concepts on this forum. However I have not seen much description of what the end goal is for concepts (maybe I missed it?).
In particular, are nimĀ“s concepts mean to be similar to the equally named work in progress C++ feature? If so, what are the differences? What is the main purpose of concepts and what is the main use case for them in nim (i.e. what do they let you do that is not possible or easy with nim without them)?
Thanks!
I did not dive deeply into concepts as they are not yet "stable" but I think this shows a bit how simple generics and concepts differ.
# a simple concept example
type Countable = concept c
inc c
dec c
type Foo = object
v: int
s: string
proc inc(a: var Foo) =
a.v += 1
proc dec(a: var Foo) =
a.v -= 1
proc twoForOneBackConcept(a: Countable): Countable =
result = a
inc result
inc result
dec result
proc twoForOneBackGeneric[T](a: T): T =
result = a
inc result
inc result
dec result
echo twoForOneBackConcept(1)
echo twoForOneBackGeneric(1)
echo twoForOneBackConcept('a')
echo twoForOneBackGeneric('a')
var x = Foo(v: 4, s: "Test")
echo twoForOneBackConcept(x)
echo twoForOneBackGeneric(x)
when false:
echo twoForOneBackConcept("Test") # will fail in this line
echo twoForOneBackGeneric("Test") # will fail at "inc" in the proc
This may be a silly question, but in the OderWat example above, on the two proc calls for type Foo (x), should x.v be updated in outer scope? i.e First echo shows (v: 5, s: Test), second echo shows (v: 5, s: Test) - on my system.
Should the second call not then echo (v: 6, s: Test) considering x passed in as 'var' ?