### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Generic: array of T  (Read 280 times)

#### bpranoto

• Full Member
• Posts: 131
##### Generic: array of T
« on: March 26, 2023, 12:21:28 pm »
Why is it not compiled?

Code: Pascal  [Select][+][-]
1. program Project1;
2. uses sysutils;
3.
4. var
5.   ATanggal:array of TDate;
6.
7. generic procedure ArrayAdd<T>( var A:array of T ; Item:T);
8. var
9.   i:Integer;
10. begin
11.   i := Length(A);
12.   SetLength(A,i+1);  // <=== Error: type mismatch
13.   A[i]:=item;
14. end;
15.
16. begin
17.   SetLength(ATanggal,0);
18.   specialize ArrayAdd<TDate>( ATanggal, Date);
19. end.
20.

• Hero Member
• Posts: 12988
##### Re: Generic: array of T
« Reply #1 on: March 26, 2023, 12:33:48 pm »
Because, again, many people do that, you are mixing up  open array parameters with dynamic arrays.
The correct way is something like this:
Code: Pascal  [Select][+][-]
1. {\$mode objfpc}{\$H+}
2. uses sysutils;
3.
4. var
5.   ATanggal:array of TDate;
6.
7. generic procedure ArrayAdd<T>( var A:specialize TArray<T> ; Item:T); // take a good look!!
8. var
9.   i:Integer;
10. begin
11.   i := Length(A);
12.   SetLength(A,i+1);  // <=== No Error
13.   A[i]:=item;
14. end;
15.
16. begin
17.   SetLength(ATanggal,0);
18.   specialize ArrayAdd<TDate>( ATanggal, Date);
19. end.

There's more wrong, but the above is close to your code and works. At least with trunk. Can't test other versions today.
« Last Edit: March 26, 2023, 12:40:32 pm by Thaddy »
I actually get compliments for being rude... (well, Dutch, but that is the same)

#### bpranoto

• Full Member
• Posts: 131
##### Re: Generic: array of T
« Reply #2 on: March 26, 2023, 12:39:20 pm »
Thank you for the enlightment.

#### bpranoto

• Full Member
• Posts: 131
##### Re: Generic: array of T
« Reply #3 on: March 26, 2023, 03:05:59 pm »
There's more wrong, but the above is close to your code and works. At least with trunk. Can't test other versions today.

it works with fpc 3.2.2