What is the meaning of a dynamic type of some value in go?

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

What is the meaning of a dynamic type of some value in go?

问题

考虑到 [tag:go] 是一种静态类型语言,某个值的动态类型是什么意思?

英文:

Considering the fact that [tag:go] is statically typed language, What is the meaning of a dynamic type of some value ?

答案1

得分: 46

变量的“动态类型”在处理接口值时非常重要。
动态类型的定义如下(来源):

变量的静态类型(或者只是类型)是由其声明定义的类型。**接口类型的变量也有一个独特的动态类型,它是变量在运行时存储的实际类型。**动态类型在执行过程中可能会变化,但始终可以赋值给接口变量的静态类型。对于非接口类型,动态类型始终是静态类型。

考虑以下示例:

var someValue interface{} = 2

someValue 的静态类型是 interface{},但动态类型是 int,并且在将来可能会发生变化。例如:

var someValue interface{} = 2

someValue = "foo"

在上面的示例中,someValue 的动态类型从 int 变为 string

英文:

The 'dynamic type' of a variable is important when handling interface values.
Dynamic types are defined as follows (source):

> The static type (or just type) of a variable is the type defined by its declaration. Variables of interface type also have a distinct dynamic type, which is the actual type of the value stored in the variable at run time. The dynamic type may vary during execution but is always assignable to the static type of the interface variable. For non-interface types, the dynamic type is always the static type.

Consider this example:

var someValue interface{} = 2

The static type of someValue is interface{} but the dynamic type is int and may very
well change in the future. Example:

var someValue interface{} = 2

someValue = "foo"

In the example above the dynamic type of someValue changed from int to string.

huangapple
  • 本文由 发表于 2013年12月11日 19:54:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/20518457.html
匿名

发表评论

匿名网友

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

确定