英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论