使用关联数组,其中值类型是 std.typecons.Nullable 的实例化
Using an associative array where the value type is an instantiation of std.typecons.Nullable
D 新手!我有两个设置函数,用于将 key/value 对输入我的 AA。一个只需要一个密钥 (K) 和一个需要一对 (K,V) 我遇到问题的是
struct SMap(K,V) {
private Nullable!(V)[K] stuff;
void set(K k){ //Issue is with this one
if(k in stuff)
stuff[k].nullify;
}
void set(K k, V v){
if(k !in stuff)
stuff[k] = v;
如果我否定该语句,那么我 运行 进入范围错误。我知道在调用 nullify 时,我会清除与 'k' 配对的值,并且我相信它将 isNull 设置为 true(如果我正确阅读了文档)
如何插入 'k' 作为具有可为空值的键?
SMap!(int,string) sm;
sm.set(2);
非常感谢任何帮助。
我最终想出的唯一可行答案如下:
if(k in stuff)
stuff[k].nullify; //I suppose that this part could actually be deleted.
else{
Nullable!(V)a; //Create a Nullable object
a.nullify; //nullify it but this part may not be needed
stuff[k] = a; //Assign to stuff[k] which sets the isNull data field to true
}
RangeError
对 if(k !in stuff) stuff[k].nullify;
很有意义。你是说 'if there is no element k
in stuff
, then do something to it.' 如果它不存在,你就不能对它做任何事情。结束.
更明确地说,您的代码是这样的:
if (k !in stuff) {
auto tmp = stuff[k]; // This line throws RangeError, since there is no element k in stuff.
tmp.nullify();
stuff[k] = tmp;
}
当然,这不是你想要的,你想将它设置为空。我可以这样建议吗:
void set(K k){
stuff[k] = Nullable!V.init;
}
D 新手!我有两个设置函数,用于将 key/value 对输入我的 AA。一个只需要一个密钥 (K) 和一个需要一对 (K,V) 我遇到问题的是
struct SMap(K,V) {
private Nullable!(V)[K] stuff;
void set(K k){ //Issue is with this one
if(k in stuff)
stuff[k].nullify;
}
void set(K k, V v){
if(k !in stuff)
stuff[k] = v;
如果我否定该语句,那么我 运行 进入范围错误。我知道在调用 nullify 时,我会清除与 'k' 配对的值,并且我相信它将 isNull 设置为 true(如果我正确阅读了文档) 如何插入 'k' 作为具有可为空值的键?
SMap!(int,string) sm;
sm.set(2);
非常感谢任何帮助。
我最终想出的唯一可行答案如下:
if(k in stuff)
stuff[k].nullify; //I suppose that this part could actually be deleted.
else{
Nullable!(V)a; //Create a Nullable object
a.nullify; //nullify it but this part may not be needed
stuff[k] = a; //Assign to stuff[k] which sets the isNull data field to true
}
RangeError
对 if(k !in stuff) stuff[k].nullify;
很有意义。你是说 'if there is no element k
in stuff
, then do something to it.' 如果它不存在,你就不能对它做任何事情。结束.
更明确地说,您的代码是这样的:
if (k !in stuff) {
auto tmp = stuff[k]; // This line throws RangeError, since there is no element k in stuff.
tmp.nullify();
stuff[k] = tmp;
}
当然,这不是你想要的,你想将它设置为空。我可以这样建议吗:
void set(K k){
stuff[k] = Nullable!V.init;
}