我想写一个通用方法来复制任何类型的列表。我的代码:
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(); };
此外,在使用list of untyped
:定义方法copy_list
时也存在错误
Error: 'list_a' is of type 'list of uint', while expecting
type 'list of untyped'.
你能帮我写一个复制列表的通用方法吗?感谢您的帮助
我认为你的方法考虑过度了。您应该只使用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
不会(因为它是一个新列表,只包含创建时包含的值list1
)。
有什么理由不使用pseudo-method.copy()吗?
var list_a : list of uint;
gen list_a;
var list_b : list of uint;
list_b = list_a.copy();