英文:
Conversion among struct types with unexported fields
问题
根据你提供的内容,以下是翻译的结果:
根据类型转换的规范,我了解到:
> 非常量值 x 可以在以下情况下转换为类型 T:
> - [..]
> - 忽略结构体标签(见下文),x 的类型和 T 不是类型参数,但具有相同的底层类型。
> - [..]
根据上述规范,我原本期望以下代码可以编译通过:
package main
import "github.com/fxtlabs/date"
type Date struct {
day int32
}
func main() {
_ = date.Date(Date{12345})
}
然而,它无法通过编译,报错信息为:
cannot convert Date{…} (value of type Date) to type date.Date
请注意,"github.com/fxtlabs/date".Date
在这里被定义为:
type Date struct {
// day gives the number of days elapsed since date zero.
day int32
}
为什么它无法编译通过?是因为来自"github.com/fxtlabs/date".Date
的字段 day
是未导出的吗?如果是的话,这不应该在规范中进行说明吗?
英文:
From the specs on conversion, I read
> A non-constant value x can be converted to type T in any of these cases:
> - [..]
> - ignoring struct tags (see below), x's type and T are not type parameters but have identical underlying types.
> - [..]
From the above specs, I would have expected the following code to compile
package main
import "github.com/fxtlabs/date"
type Date struct {
day int32
}
func main() {
_ = date.Date(Date{12345})
}
However, it does not compile with error message
cannot convert Date{…} (value of type Date) to type date.Date
Note that "github.com/fxtlabs/date".Date
is defined here as
type Date struct {
// day gives the number of days elapsed since date zero.
day int32
}
Why does it fail to compile? Is it because the field day
from "github.com/fxtlabs/date".Date
is unexported? If yes, shouldn't this be specified in the specs?
答案1
得分: 3
是的。
如果是的话,这不应该在规范中进行说明吗?
在规范的类型标识部分有说明。
如果两个结构体类型具有相同的字段顺序,并且相应的字段具有相同的名称、相同的类型和相同的标签,则它们是相同的。来自不同包的非导出字段名称始终是不同的。
换句话说,这些底层类型是不相同的,因为它们的字段是未导出的。
相同类型的示例:struct {Day int32}
(包a)和struct{Day int32}
(包b)。
不相同类型的示例:struct {day int32}
(包a)和struct{day int32}
(包b)。
英文:
> Is it because the field day from "github.com/fxtlabs/date".Date is unexported?
Yes.
> If yes, shouldn't this be specified in the specs?
It is in the spec under Type Identity.
>Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Non-exported field names from different packages are always different.
In other words, the underlying types are NOT identical because their fields are unexported.
Example of identical types struct {Day int32}
(packag a) and struct{Day int32}
(package b).
Example of NOT identical types struct {day int32}
(packag a) and struct{day int32}
(package b).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论