自定义命名类型的转换函数是语言构造还是函数?

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

Are custom named type's conversions functions or language construct

问题

我无法找到关于这个功能的具体文档(我在一些代码示例中看到了这个功能)。

type Event string
type Num int

func main() {
    foo := Event("my event")
    bar := Num(45)
}

Go语言是否会为每个自定义命名类型动态创建自定义命名函数(转换函数)?

英文:

I am unable to find any specific documentation for this feature (which I see in some code examples).

type Event string
type Num int

func main() {
	foo := Event("my event")
	bar := Num(45)
}

Is Go dynamically creating custom-named functions (conversion functions?) for each custom-named type?

答案1

得分: 1

不,这是语言规范定义的转换表达式。

  • Event 是一个定义的类型,定义为 type Event string
  • "my event" 是一个字符串字面量
  • 语法 <type>(<expression>) 是一种类型转换

显式转换是形式为 T(x) 的表达式,其中 T 是一个类型,x 是可以转换为类型 T 的表达式。

字面量是一个常量表达式(只有一个操作数)。

如果常量值 x 可以由 T 类型的值表示,则可以将其转换为类型 T

字符串字面量 "my event" 是否可以表示为 Event 值?是的,因为 Event 的底层类型是 string

英文:

> Is Go dynamically creating custom-named functions (conversion functions?)

No, it's a conversion expression defined by the language specs.

  • Event is a defined type, defined as type Event string
  • &quot;my event&quot; is a string literal
  • the syntax &lt;type&gt;(&lt;expression&gt;) is a type conversion.

> An explicit conversion is an expression of the form T(x) where T is a type and x is an expression that can be converted to type T.

A literal is a constant expression (with just one operand).

> A constant value x can be converted to type T if x is representable by a value of T.

Is the string literal &quot;my event&quot; representable by an Event value? Yes, because Event's underlying type is string.

huangapple
  • 本文由 发表于 2021年7月5日 17:40:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/68253874.html
匿名

发表评论

匿名网友

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

确定