d结构用要求

原文

import std;

struct A
{
    double val;
    bool isBig;
}


void main() {
    alias DListOfA = DList!A;
    DListOfA[string] temp;
    A a = {2.0, true};

    DListOfA returnVal = temp.require("a", DListOfA());//--> 这里希望用DListOfA的引用

    returnVal.insert(a);
    writeln(temp);
}

参考
希望能够这样:

ref DListOfA returnVal = ....

但是不能保持临时引用,因为临时在该表达式的末尾结束(实际上是在分号处).
或者用new动态分配对象(并将DListOfA*存储在关联数组中).然后,只要指针在关联数组中,GC就会让它保持活动状态.
更好选择是忘记它,因为D已经通过默认blitting(位级复制)来处理右值.一切正常…:)它也不贵.例如,复制结构很便宜.
但我可能错过了你想要ref的原因.也许还有更好的选择.

使用指针:

DListOfA *returnVal = &temp.require(...);
returnVal.insert(a);

这样:

import object, std.container;

struct A
{
    double val;
    bool isBig;
}

void main()
{
  alias DListOfA = DList!A;
  DListOfA returnVal;
  //DListOfA[string] temp;
  DListOfA[string] temp = [
    "a": DListOfA( A(0) )
   ];//*/
  
  auto a = A(6, true); // replacement element
  temp.update("a", {
    return DListOfA( A(0) ); // not updated: unsucceeded but initialized
   }, (ref DListOfAv) {
    v = DListOfA( a ); // existing v has been replaced
    returnVal = v;
        assert(returnVal.front == a);
   });
  assert(is(typeof(temp["a"]) == DList!A));
}
posted @   zjh6  阅读(21)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示