gpt4 book ai didi

D: 如何从main 退出?

转载 作者:行者123 更新时间:2023-12-04 09:25:39 32 4
gpt4 key购买 nike

终止/退出主函数的 D 方式是什么?

import std.stdio;
import core.thread;

void main()
{
int i;
while (i <= 5)
{
writeln(i++);
core.thread.Thread.sleep( dur!("seconds")(1) );
}
if (i == 5)
{
writeln("Exit");
return; // I need terminate main, but it's look like break do exit only from scope
}
readln(); // it's still wait a user input, but I need exit from App in previous step
}

我试着用谷歌搜索,发现下一个问题 D exit statement
有建议使用 C 退出函数。现代 D 中是否有任何新的 future ,可以让它更优雅?

最佳答案

如果你不做紧急导出,那么你想清理一切。我创建了一个 ExitException以此目的:

class ExitException : Exception
{
int rc;

@safe pure nothrow this(int rc, string file = __FILE__, size_t line = __LINE__)
{
super(null, file, line);
this.rc = rc;
}
}

您编码您的 main()功能然后喜欢
int main(string[] args)
{
try
{
// Your code here
}
catch (ExitException e)
{
return e.rc;
}
return 0;
}

在你需要退出的时候你打电话
throw new ExitException(1);

关于D: 如何从main 退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054713/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com