初化d构

  auto ms1 = MyStruct(10, 11);// struct literal,一般简单.
  MyStruct ms2 = {10, 11};    // C-style, not preferred
  MyStruct ms3 = {b:11, a:10};// Named initializers

立刻初化完:

 import std.stdio;

  struct Point {
      int x, y;

      string toString() {
          import std.format : format;

          return format("(%d, %d)", x, y);
      }
  }

  void main() {
      Point[2] ps = [{0,0}, {4,4}];
      foreach (p; ps) writeln(p);
  }

自定义:


  #! /usr/bin/env rdmd
  import std.stdio;

  struct X {
      int a;

      this(int x) {
          a = x * 2;
      }
  }

  void main() {
      auto test = X(22);
      writeln(test.a);
  }

output: 44
struct Foo {
    int x;

    this(int a, int b) { x = a + b; }//有它,foo(a)就不行,无它,就可以
}
struct S
{
    int x;
}

auto s = S(42);

改成:

struct S
{
    int x;
    int y;
}

auto s = S(42);
//仍然编译
struct S
{
    string s;
    int i;
}

auto s = S("hello", 42);

struct S
{
    string s;
    int foo;
    int i;
}

auto s = S("hello", 42);//编译不过

struct S
{
    int x;
    int y;
}

auto s = S(12, 99);

//构字面量导致漏洞.应声明构造器.

struct S
{
    int y;
    int x;
}

auto s = S(12, 99);
posted @   zjh6  阅读(13)  评论(0编辑  收藏  举报  
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示