简体   繁体   中英

Does D distinguish between return/argument types of dynamic vs. static arrays?

Suppose I define a function, mutate, which replaces a random index's contents of an int array, a , with some function applied

int[] mutate(int[] a) {
    int randomIndex = cast(int) uniform(a[randomIndex]);
    a[randomIndex] = a[randomIndex] + 1;
    return a;
}

Does this function specify input and return values of dynamic int array, static int array, or both? That is, is this function limited to accepting and returning either subtype of array? Is there a way to distinguish between dynamic and static arrays as arguments to a function?

Do either of the following throw an error?

void main() {
    int[] dyn;
    dyn = [1, 2, 3];
    writeln(mutate(dyn));

    int[3] stat = [1,2,3];
    writeln(mutate(stat));
}
 int[] mutate(int[] a) 

That takes a slice and returns a slice. A slice is not necessarily a dynamic array, it might be a static array, though then you need to pass it as stat[] instead of just stat .

A slice is like a ptr and length combo in C: a pointer to data (which may reside anywhere, a dynamic array, a malloc array, a static array, some block of memory, whatever) and a count of the length.

When you return one like that, you do need to be kinda careful not to store it. The slice doesn't know where it is stored and you might easily lose track of who owns it and end up using a bad pointer! So be sure the scope is safe when doing something like this.

Read this for more info:

http://dlang.org/d-array-article.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM