首页 > 解决方案 > 如何在 Ada 中生成唯一的 id?

问题描述

我正在从事 Ada 项目,我正在尝试生成一个唯一 ID,该 ID 将用作一个人的唯一标识符。我想知道是否有办法在 Ada 中生成唯一 ID?

标签: uuidadauniqueidentifier

解决方案


您确实没有指定很多要求,所以如果您只需要快速简单的东西,您可以使用私有包变量并让生成器函数返回当前值,然后将其更新为新值。

with Ada.Text_IO; use Ada.Text_IO;

procedure Hello is

    package IDs is
        type ID is mod 2**64;
        function New_ID return ID;
    end IDs;

    package body IDs is
        Current : ID := 0;
        function New_ID return ID is
        begin
            return Result : ID := Current do
                Current := Current + 1;
            end return;
        end New_ID;
    end IDs;
begin
   Put_Line("Hello, world!");
   Put_Line("New ID =>" &  IDs.ID'Image(IDs.New_ID));
   Put_Line("New ID =>" &  IDs.ID'Image(IDs.New_ID));
end Hello;

输出:

$gnatmake -o hello *.adb
gcc -c hello.adb
gnatbind -x hello.ali
gnatlink hello.ali -o hello
$hello
Hello, world!
New ID => 0
New ID => 1

如果您需要它的任务安全,则将“当前”变量包装在受保护的对象中。它最多只能生成 2**64 个唯一 ID,但如果您的编译器支持更大的数据类型,您可以更改它。


推荐阅读