Can I write a function that takes a static array of chars in D?

98 Views Asked by At

for example, i want to write a function with this signature: int foo(char[]) and to call it using char[5] x; foo(x).

At the moment i get a compile error stating that char[] isn't the same as char[5].

I thought of writing: int foo(uint SIZE)(char[SIZE]) but then I have to explicitly set the length when calling foo: foo!5(x) for the example before.

EDIT: you guys are correct, my function actually looks like foo(ref char[]) and I have declared it @nogc. What I want to do is to fill a given static array with data. In a broader sense, I'm trying to implement a degenerate format function because the standard library one is definitely using the GC and I can't call it from my other non GC code. Any ideas about that as well?

1

There are 1 best solutions below

0
DejanLekic On BEST ANSWER

char[] is indeed not the same as char[5], but nothing prevents you from passing static array as an argument to a function which has char[] parameter because of the implicit conversion.

Example:

module so.d26013262;

import std.stdio;

int getSize(int[] arr) {
    return arr.length;
}

void main(string[] args) {
    int[5] starr;
    int[] dyarr = [1, 3, 2];

    writeln(getSize(starr));
    writeln(getSize(dyarr));
}

Output:

5
3

My guess is that you are getting error somewhere else...