我想写一个复制任何类型列表的通用方法。 我的代码:
copy_list(in_list : list of rf_type) : list of rf_type is {
var out_list : list of rf_type;
gen out_list keeping { it.size() == in_list.size(); };
for each (elem) in in_list {
out_list[index] = elem.unsafe();
};
result = out_list;
};
该方法的调用:
var list_a : list of uint;
gen list_a;
var list_b : list of uint;
list_b = copy_list(list_a);
错误:
ERR_GEN_NO_GEN_TYPE: Type 'list of rf_type' is not generateable
(it is not a subtype of any_struct) at line ...
gen out_list keeping { it.size() == in_list.size(); };
此外,使用copy_list
定义方法list of untyped
时也会出错:
Error: 'list_a' is of type 'list of uint', while expecting
type 'list of untyped'.
你能帮忙写一个通用方法来复制列表吗?感谢您的帮助
答案 0 :(得分:4)
我认为你过度思考自己的方法。您应该只使用copy()
伪方法:
extend sys {
run() is also {
var list1 : list of uint = { 1; 2; 3 };
var list2 := list1; // shallow copy, list2 points to list1
var list3 : list of uint = list1.copy();
list1.add(4);
print list1, list2, list3;
};
};
如果您运行该示例,则会看到list2
将包含4(因为它仅仅是list1
的引用,而list3
赢了&# 39; t(因为它是一个新列表,只包含创建时包含的值list1
)。
答案 1 :(得分:2)
有没有理由不使用伪方法.copy()?
var list_a : list of uint;
gen list_a;
var list_b : list of uint;
list_b = list_a.copy();