dlang ref的作用

ref 作用

 1 import std.stdio, std.string;
 2 
 3 void main()
 4 {
 5     string[] color=["red","blue","cyan","grey"];
 6     
 7     writeln("raw:",color);
 8     write("m1:");
 9     m1(color);
10     write("m2:");
11     m2(color);
12 }
13 
14 void m1(string[] color)
15 {
16     foreach(string col; color)
17     {
18         if(col=="red") // 此处col是color中每个元素的copy,直接赋值无法改变原来数组
19         {
20             col="tomato"; 
21         }
22     }
23     writeln(color);
24 }
25 
26 void m2(string[] color)
27 {
28     foreach(ref string col; color) //添加ref修饰,可直接作用到原数组元素
29     {
30         if(col=="red") 
31         {
32             col="tomato";
33         }
34     }
35     writeln(color);
36 }

 

posted @ 2020-12-17 20:04  天使不设防  阅读(132)  评论(0编辑  收藏  举报