类型转换规则 – 将类型转换为其基础类型

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

Type conversion rule - Converting a type to its underlying type

问题

在将一个对象(type1)的成员复制到另一个对象(type2)的成员时,遇到了以下情况:

package main

import "fmt"

type SomeType string

func main() {
    source := SomeType("abc")
    dest := string(source) // 这个可以工作
    fmt.Println(dest)
}

对于这种类型转换(string(source)),根据Go规范中的哪个规则进行转换到底层类型?

英文:

Got into below scenario amidst copying one object(type1) members to another object(type2) member:

package main

import "fmt"

type SomeType string

func main() {
	source := SomeType("abc")
	dest := string(source) // this works 
	fmt.Println(dest)
}

For this type conversion(string(source)), which rule from Go spec is applied, for conversion to underlying type?

答案1

得分: 8

如果你阅读有关转换的内容,你会看到非常量转换的规则。第一个规则适用于以下情况:

  • x可以赋值给T。

并且链接到可赋值性部分。而在那里,相关的部分是:

英文:

If you read about conversions, you'll see the rules for non-constant conversions. The first one applies:

> - x is assignable to T.

and links to the section on assignability. In turn, the relevant bit there is:

> - x's type V and T have identical underlying types and at least one of V or T is not a defined type.

huangapple
  • 本文由 发表于 2021年6月25日 19:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/68130520.html
匿名

发表评论

匿名网友

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

确定