Union types in runtime 在运行时的联合类型

huangapple go评论53阅读模式
英文:

Union types in runtime

问题

请解释编译器如何生成在运行时适用于联合类型的代码。例如,我有这段 Crystal 代码:

def myfunc : Int32 | String
  if Time.utc.to_unix % 2 == 0
    return 1
  else
    return "a"
  end
end

x : (Int32 | String) = myfunc
puts x * 2

我有一个函数,可以返回 int 或 string 中的任意一种。在运行时,我不知道会得到哪种类型。但我有一个 * 函数,对不同类型有不同的行为。对于 int,它只是将数字加倍(得到 2),但对于 string,它将字符串连接起来(得到 "aa")。

在运行时,我们如何知道我们应该对 x 中的值执行什么操作,因为在运行时没有类型信息呢?

英文:

Can anyone explain how the compiler generates the code that will work for union types in runtime. For example, I have this crystal code:

def myfunc : Int32 | String
  if Time.utc.to_unix % 2 == 0
    return 1
  else
    return "a"
  end
end

x : (Int32 | String) = myfunc
puts x * 2

I have a function that can return either int or string. And I do not know what type I will have until runtime. But I have "*" function that has different behaviour for different types. For int it just doubles the number (we get 2), but for string it concatenates the string (we get "aa").
How do we know in runtime what actually should we do with the value in x since we do not have types in runtime?

答案1

得分: 2

联合类型值嵌入了一个描述其类型的类型标识符,在运行时可以使用未记录的方法 Object#crystal_type_id 访问此信息。

然后,联合类型的 #* 方法实现使用多重分派来调用相应运行时类型的实现。
可以将其理解为类似于以下内容:

fun "(Int32 | String)#*"(args)
  case crystal_type_id
  when String.crystal_instance_type_id
    "String#*"(args)
  when Int32.crystal_instance_type_id
    "Int32#*"(args)
  end
end
英文:

The union type value has a type id embedded which describes at runtime which type it is (this information is available as an undocumented method Object#crystal_type_id).

The implementation of the union types' #* method then uses multi dispatch to call the respective runtime types' implementation.
It can be thought of as somethign like this:

fun "(Int32 | String)#*"(*args)
  case crystal_type_id
  when String.crystal_instance_type_id
    "String#*"(*args)
  when Int32.crystal_instance_type_id
    "Int32#*"(*args)
  end
end

huangapple
  • 本文由 发表于 2023年7月3日 15:50:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定